我正在尝试从 URL 获取 JSON 数据,并且我已通过浏览器检查了该 URL,它显示了有效的 JSON 数据,同时,如果我执行相同操作,则会收到以下错误:
Illegal character in query at index 47: http://bangladeshelections.org/candidate?where={
索引 47 是 where 之后的第一个大括号。
我尝试了以下代码来获取 URL
此处,值是来自前一个 Activity 的数组。
District = value[0];
Municipality = value[1];
Type = value[2];
Ward = value[3];
url_all_products = url_all_products + "District\":\""+District+"\",\"Municipality\":\""+
Municipality+"\",\"Type\":\""+Type+"\",\"Ward\":\""+Ward+"\"}";
Log.i("Monkey", url_all_products.charAt(47) + "bulls");
new LoadAllProducts(getApplicationContext()).execute();
我使用以下代码在异步线程中获取 JSON 数据
URL url = new URL(url_all_products);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url_all_products));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
谢谢。
最佳答案
您的查询字符串使用非法字符 - 在没有外部库的情况下避免这种情况的最简单方法是使用 java.net.URI
从其组件构造您的 URL。它包含一个接受查询字符串并将为您执行正确编码的构造函数。例如编码:
http://host.com/path?query=queryparam#fragment
new URI("http", "host.com", "/path/", "query=queryparam", "fragment").toURL();
请参阅文档
关于java - URL 连接中的查询中存在非法字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34386484/