拼接地址创建HttpClient的时候,出现了java.net.URISyntaxException: Illegal character in scheme name at index 0:错误
HttpGet get = new HttpGet("https://api.mch.weixin.qq.com/v3/pay/transactions/id/" + orderId + "?mchid=1111111111");
当路径有 ‘?’ 、’&’、 ‘|’ 等字符的时候就会出现 Illegal character in scheme name at index 0错误,查看源码
public HttpGet(final String uri) {
super();
setURI(URI.create(uri));
}
可以发现里面是使用URI.create(uri)进行创建
因为在转化的时候涉及编码问题,所以我们可以使用URL间接转为URI
/**
* 将地址变成URI形式
*
* @param path 请求地址
* @return uri
*/
private static URI getUri(String path) {
URI uri = null;
try {
URL url = new URL(path);
uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null);
} catch (MalformedURLException | URISyntaxException e) {
e.printStackTrace();
}
return uri;
}