您的位置:首页 > 产品设计 > UI/UE

Exception in thread "main" java.lang.IllegalArgumentException: Illegal character in query at index x

2017-10-20 15:40 525 查看

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); 更多可查看:点击打开链接
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐