解决异常 java.net.URISyntaxException: Illegal character in query at index

在String型的url中包含("&"、"|"、"-")这些字符直接用HttpClient请求就会报错URISyntaxException: Illegal character

解决方式:

不能直接用String代替URI来访问。必须采用%0xXX方式来替代特殊字符(转义)。

但这种办法不直观。所以只能先把String转成URL,再能过URL生成URI的方法来解决问题。代码如下:

String strUrl = "http://baidu.action?key2=xxxxx";

URL url = new URL(strUrl);
URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null);

//向对应的网址发送GET请求,判断返回码
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet(uri);
HttpResponse httpResponse = httpClient.execute(httpGet);;
int code = httpResponse.getStatusLine().getStatusCode();

猜你喜欢

转载自blog.csdn.net/weixin_49343190/article/details/122626985
今日推荐