看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參數才能生效。
新聞熱點
疑難解答