我在做什么: 我正在尝试在 android 中进行反向地理编码
我得到的错误是: java.lang.IllegalArgumentException:索引 59 处查询中的非法字符:http://maps.google.com/maps/api/geocode/json?address=Agram , 类加罗尔, 卡纳塔克邦, 印度&sensor=false
注意:该请求在浏览器中获得 json 响应,但不是来 self 下面的类
此行出现此错误::
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;
}
}
最佳答案
使用URLEncoder.encode()
在将 address
参数 "Agram, Bengaluru, Karnataka, India"
的值放入 URL 字符串之前对其进行编码,使其变成类似于
http://maps.google.com/maps/api/geocode/json?address=Agram,+Bengaluru,+Karnataka,+India&sensor=false
即空格更改为 +
,其他特殊八位字节表示为 %xx
。
浏览器会自动对地址栏中输入的字符串进行智能 URL 编码,这就是它在那里工作的原因。
关于java.lang.IllegalArgumentException : Illegal character in query at index 59 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27126839/