这是我修改的代码对原始url做编码: String a = "friend.renren.com/shareFriends?t=0.2351487116323684&p={%22init%22:true,%22uid%22:true,%22uhead%22:true,%22uname%22:true,%22group%22:true,%22net%22:true,%22param%22:{%22guest%22:292794698}}"; try{ String c = URLEncoder.encode(a,"UTF-8"); String d = "http://" + c; System.out.println(notify.notify(d)); } catch (UnsupportedEncodingException ex) { throw new RuntimeException("Broken VM does not support UTF-8"); } 可是又出现了异常: Exception:java.lang.NumberFormatException: For input string: "true,%22uid%22:true,%22uhead%22:true,%22uname%22:true,%22group%22:true,%22net%22:true,%22param%22:{%22guest%22:292794698}}" 不知道为什么,是该url中传递参数出了问题吗?为什么谷歌浏览器就可以打开~~
java.net.URISyntaxException的解决办法近日在用HttpClient访问抓取汇率时,为了省力,直接采用 String url = "http://api.liqwei.com/currency/?exchange=usd|cny&count=1"; HttpClient client = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); HttpResponse response = client.execute(httpget);
以前用这种方法都没有问题,但这次却报如下错误: java.net.URISyntaxException: Illegal character in query at index 44
查找了一些网上资料,说地址中涉及了特殊字符,如‘|’‘&’等。所以不能直接用String代替URI来访问。必须采用%0xXX方式来替代特殊字符。但这种办法不直观。所以只能先把String转成URL,再能过URL生成URI的方法来解决问题。代码如下 URL url = new URL(strUrl); URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null); HttpClient client = new DefaultHttpClient(); HttpGet httpget = new HttpGet(uri);
String a = "friend.renren.com/shareFriends?t=0.2351487116323684&p={%22init%22:true,%22uid%22:true,%22uhead%22:true,%22uname%22:true,%22group%22:true,%22net%22:true,%22param%22:{%22guest%22:292794698}}";
try{
String c = URLEncoder.encode(a,"UTF-8");
String d = "http://" + c;
System.out.println(notify.notify(d));
}
catch (UnsupportedEncodingException ex) { throw new RuntimeException("Broken VM does not support UTF-8");
}
可是又出现了异常:
Exception:java.lang.NumberFormatException: For input string: "true,%22uid%22:true,%22uhead%22:true,%22uname%22:true,%22group%22:true,%22net%22:true,%22param%22:{%22guest%22:292794698}}"
不知道为什么,是该url中传递参数出了问题吗?为什么谷歌浏览器就可以打开~~
“{” => %7B
“}” => %7D
String url = "http://api.liqwei.com/currency/?exchange=usd|cny&count=1";
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = client.execute(httpget);
以前用这种方法都没有问题,但这次却报如下错误:
java.net.URISyntaxException: Illegal character in query at index 44
查找了一些网上资料,说地址中涉及了特殊字符,如‘|’‘&’等。所以不能直接用String代替URI来访问。必须采用%0xXX方式来替代特殊字符。但这种办法不直观。所以只能先把String转成URL,再能过URL生成URI的方法来解决问题。代码如下
URL url = new URL(strUrl);
URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null);
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(uri);