java.lang.IllegalArgumentException: Illegal character in query

回眸只為那壹抹淺笑 提交于 2019-11-30 05:25:58

So I ended up changing my code from:

    String placesSearchStr="https://maps.googleapis.com/maps/api/place/nearbysearch/"
    +"json?location="
    +String.valueOf(lat)
    +","
    +String.valueOf(lng)
    +"&radius=5000&sensor=true"
    +"&types=food|bar|church|museum|art_gallery"
    +"&key=AIzaSyDdMnQpqT9pr-k6VhwesT1OBAg_qkvflxU";

to:

String latVal=String.valueOf(lat);
String lngVal=String.valueOf(lng);
String url;
try {
        url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="
        +URLEncoder.encode(latVal, "UTF-8")
        +","
        +URLEncoder.encode(lngVal, "UTF-8")
        +"&radius="
        +URLEncoder.encode("5000", "UTF-8")
        +"&sensor="
        +URLEncoder.encode("true", "UTF-8")
        +"&types="
        +URLEncoder.encode("food|bar|church|museum|art_gallery", "UTF-8")
        +"&key="
        +URLEncoder.encode("AIzaSyDdMnQpqT9pr-k6VhwesT1OBAg_qkvflxU", "UTF-8");
        new GetPlaces().execute(url);
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

And this solved my problem.

If you would like to use a Java library that handles these HTTP details for you and allows you to interact with the Google Places API through Java methods and objects, you can try Sprockets (disclosure: I'm the developer).

I'm also working on an Android library project that will include Loaders, Adapters, and widgets for use with the Google Places API.

Note that when using Sprockets in Android, you will most likely want to use ProGuard for release builds to strip out the unused code in the dependency libraries (see the POM for dependencies).

Try using String.valueOf() when adding the lat & long. It may be leaving extra stuff in there that's causing you trouble when trying to parse it that is getting cut out when the string is being displayed.

String placesSearchStr = new String(
    "https://maps.googleapis.com/maps/api/place/nearbysearch/"
    +"json?location="
    +String.valueOf(lat)
    +","
    +String.valueOf(lng)
    +"&radius=5000&sensor=true"
    +"&types=food|bar|store|museum|art_gallery"
    +"&key=AIzaSyDdMnQpqT9pr-k6VhwesT1OBAg_qkvflxU"
    ,"UTF-8");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!