看HttpClient的源代码可以发现URI是个线索,在execute方法中会判断URI中设置的是否是绝对路径还是相对路径,如果是相对路径时httpclient会将defaulthost+uri拼接为完整的请求地址。如果URI中设置了scheme并且URI配置了host就会用URI完整的绝对路径作为请求地址。判断逻辑如下
public final HttPResponse execute(HttpUriRequest request, HttpContext context) throws IOException, ClientProtocolException { if (request == null) { throw new IllegalArgumentException ("Request must not be null."); } return execute(determineTarget(request), request, context);}private static HttpHost determineTarget(HttpUriRequest request) throws ClientProtocolException { // A null target may be acceptable if there is a default target. // Otherwise, the null target is detected in the director. HttpHost target = null; URI requestURI = request.getURI(); if (requestURI.isAbsolute()) { target = URIUtils.extractHost(requestURI); if (target == null) { throw new ClientProtocolException( "URI does not specify a valid host name: " + requestURI); } } return target;}分析完就找到了方法解决问题了,在请求时设置URI即可,要注意的是build URI的时候要配置scheme参数才能生效。
新闻热点
疑难解答