0

我有一个问题,当我调用带有许多 JSON 响应参数的 url 时,它会显示一个 URISyntaxError 但相同的 url 在所有浏览器上都可以正常工作。我无法理解出了什么问题?

The URL is: http://apibeta.highgearmedia.com/v1/vehicles/get-make-models.json?sort=mpg&filter=category&client-id=10030812&from=convertible&signature=QOwiWhG2T47KaQoyUztbag==

代码:

HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(api_url));

            HttpResponse response = client.execute(request);
            InputStream ips = response.getEntity().getContent();
            BufferedReader buf = new BufferedReader(new InputStreamReader(ips,
                    "UTF-8"));

            StringBuilder sb = new StringBuilder();
            String s;
            while (true) {
                s = buf.readLine();
                if (s == null || s.length() == 0)
                    break;
                sb.append(s);

            }
            buf.close();
            ips.close();
            return sb.toString();

错误:

05-10 23:03:45.326: W/System.err(2227): java.net.URISyntaxException: Illegal character in query at index 161: http://apibeta.highgearmedia.com/v1/vehicles/get-make-models.json?sort=mpg&filter=category&client-id=10030812&from=convertible&signature=QOwiWhG2T47KaQoyUztbag==
05-10 23:03:45.326: W/System.err(2227):     at java.net.URI.validateQuery(URI.java:434)
05-10 23:03:45.326: W/System.err(2227):     at java.net.URI.parseURI(URI.java:340)
05-10 23:03:45.335: W/System.err(2227):     at java.net.URI.<init>(URI.java:72)
05-10 23:03:45.335: W/System.err(2227):     at com.TCC.android.ResearchList.getJsonSring(ResearchList.java:3892)
05-10 23:03:45.335: W/System.err(2227):     at com.TCC.android.ResearchList$67.run(ResearchList.java:4077)
4

2 回答 2

2

如果您的问题,这是一个解决方案,该函数将从 url 中删除所有无效字符。在此函数中传递您的 url,您将获得一个带有编码字符串的新 url。

public static String convertURL(String str) {

    url = null;
    try{
    url = new String(str.trim().replace(" ", "%20").replace("&", "%26")
            .replace(",", "%2c").replace("(", "%28").replace(")", "%29")
            .replace("!", "%21").replace("=", "%3D").replace("<", "%3C")
            .replace(">", "%3E").replace("#", "%23").replace("$", "%24")
            .replace("'", "%27").replace("*", "%2A").replace("-", "%2D")
            .replace(".", "%2E").replace("/", "%2F").replace(":", "%3A")
            .replace(";", "%3B").replace("?", "%3F").replace("@", "%40")
            .replace("[", "%5B").replace("\\", "%5C").replace("]", "%5D")
            .replace("_", "%5F").replace("`", "%60").replace("{", "%7B")
            .replace("|", "%7C").replace("}", "%7D"));
    }catch(Exception e){
        e.printStackTrace();
    }
    return url;
}
于 2012-05-10T19:27:04.617 回答
0

根据java URI javadoc和底层RFC(第 2.2 和 3.4 节),=是一个保留字符,应该转义(%3Dfor =

顺便说一句,你应该使用android.net.URI

于 2012-05-10T18:00:09.400 回答