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

标签 java android json parsing

我正在尝试从 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/

相关文章:

java - 如何使用 Spring 注入(inject)网络文件资源?

android - Webview Android 超时

java - 安卓,http : How to upload a file to a site hosted by a shared server?

java - BIRT 运行时 4.6.0 运行 genReport 时出错

java - 如何根据父级动态生成 JPA Id 列?

JSON 到 R 数据帧 : preserve repeated values

java - HTTP 传输和 HTTP 请求

android - 在通过 Google 登录 Google Play 商店发布 Xamarin 应用程序时,应使用哪个 SHA-1 key ?

java - 在 Webview 上启用 GeoLocation

javascript - 如何在 JavaScript 中调用 Python 变量?