java.lang.IllegalArgumentException:索引59处查询中的非法字符

时间:2014-11-25 12:31:29

标签: java android json google-maps

我在做什么: 我想在android中进行反向地理编码

我收到错误:: java.lang.IllegalArgumentException:索引59处的查询中的非法字符:http://maps.google.com/maps/api/geocode/json?address=Agram,Bengaluru,印度卡纳塔克邦& sensor = false

NOte:该请求在浏览器中获取json响应,但不在我的下面的类中

此行显示此错误::

HttpGet httpget = new HttpGet(url);

JSONfunctions.java

public class JSONfunctions {

    public static JSONObject getJSONfromURL(String url) {
        InputStream is = null;
        String result = "";
        JSONObject jArray = null;

        // Download JSON data from URL
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(url);

            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }

        // Convert response to string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }

        try {

            jArray = new JSONObject(result);
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }

        return jArray;
    }
}

3 个答案:

答案 0 :(得分:14)

使用URLEncoder.encode()address参数"Agram, Bengaluru, Karnataka, India"的值进行编码,然后再将其放入网址字符串中,使其变为类似

http://maps.google.com/maps/api/geocode/json?address=Agram,+Bengaluru,+Karnataka,+India&sensor=false

即。空格更改为+,其他特殊八位字节更改为%xx

浏览器会自动对地址栏中输入的字符串进行智能URL编码,这就是它在那里工作的原因。

答案 1 :(得分:6)

建立您的网址,

final StringBuilder request = new StringBuilder(
        "http://maps.googleapis.com/maps/api/geocode/json?sensor=false");
request.append("&language=").append(Locale.getDefault().getLanguage());
request.append("&address=").append(
        URLEncoder.encode(locationName, "UTF-8"));

答案 2 :(得分:1)

  

我正在使用httpclient 4.3.3

String messagestr = "Welcome to Moqui World";
String url="http://my.example.com/api/sendhttp.phpauthkey="+URLEncoder.encode("17djssnvndkfjb110d3","UTF-8")+"&mobiles=91"+URLEncoder.encode(contactNumber,"UTF-8")+"&message="+URLEncoder.encode(messagestr,"UTF8")+"&sender="+URLEncoder.encode("WMOQUI","UTF-8")+"&route=4";

HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);

这对我来说很好。我希望这对你有帮助。