gpt4 book ai didi

java - URL 连接中的查询中存在非法字符

转载 作者:行者123 更新时间:2023-12-01 10:41:25 26 4
gpt4 key购买 nike

我正在尝试从 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();

请参阅文档

http://docs.oracle.com/javase/6/docs/api/java/net/URI.html

关于java - URL 连接中的查询中存在非法字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34386484/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com