HttpClient:
超文本傳輸協定(HTTP)可能是當今網際網路上使用的最重要的協定。Web服務,啟用網絡的裝置和網絡計算的增長繼續擴充了HTTP協定在使用者驅動的Web浏覽器之外的作用,同時增加了需要HTTP支援的應用程式的數量。
Exception in thread "main" java.lang.IllegalArgumentException: Illegal character in query at indexxx. 在請求第三方接口時發生了如下錯誤,并且參數格式都是正确的,通過翻閱一些資料,定位是請求前進行編碼。
代碼如下:
public static String post(String url , Map params) throws Exception {
//String encode = URLEncoder.encode(JSON.toJSONString(params),"UTF-8");
HttpClient client = HttpClients.createDefault();
HttpPost httppost = new HttpPost(new StringBuilder().append(url+JSON.toJSONString(params).toString());
logger.info(String.format("URI:%s",httppost.getURI()));
HttpResponse res = client.execute(httppost);
String result ="";
HttpEntity entity = res.getEntity();
if (entity != null)
result = EntityUtils.toString(entity, "UTF-8");
return result;
}
錯誤:Exception in thread "main" java.lang.IllegalArgumentException: Illegal character in query at index 6.....
原因:參數需要編碼後然後發送請求,完整代碼如下:
public static String post(String url , Map params) throws Exception {
String encode = URLEncoder.encode(JSON.toJSONString(params),"UTF-8");
HttpClient client = HttpClients.createDefault();
HttpPost httppost = new HttpPost(new StringBuilder().append(url+encode).toString());
logger.info(String.format("URI:%s",httppost.getURI()));
HttpResponse res = client.execute(httppost);
String result ="";
HttpEntity entity = res.getEntity();
if (entity != null)
result = EntityUtils.toString(entity, "UTF-8");
return result;
}
編碼後的參數列印在控制台了:URI:http://xxxx:8080/testmethod=test¶ms=%7B%22vo%22%3A%7B%22shownum%22%3A
由于太長以上copy了一部分。
還有一種方式來請求:
URI uri = new URIBuilder()
.setScheme("http")
.setHost("www.google.com")
.setPath("/search")
.setParameter("q", "httpclient")
.setParameter("btnG", "Google Search")
.build();
HttpGet httpget = new HttpGet(uri);
更多可檢視: 點選打開連結