Solve exception java.net.URISyntaxException: Illegal character in query at index

If a String-type url contains ("&", "|", "-") these characters, an error will be reported directly with the HttpClient request URISyntaxException: Illegal character.

Solution:

You cannot directly use String instead of URI to access. Special characters (escaping) must be replaced by %0xXX.

But this approach is not intuitive. Therefore, we can only convert String into URL first, and then we can solve the problem by generating URI from URL. code show as below:

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();

Guess you like

Origin blog.csdn.net/weixin_49343190/article/details/122626985