问题描述:
使用HttpClient进行http请求,每次请求随机使用一个target host进行请求。
发http请求的时候,一般会配置数据源,设置ClientPNames.DEFAULT_HOST,这样在请求的时候目标机器host和端口就是配置的ClientPNames.DEFAULT_HOST。但是不能每次请求ClientPNames.DEFAULT_HOST,因为一个httpclient就对应一个ClientPNames.DEFAULT_HOST,就无法针对一次request进行目标host的修改。
例如:
HttpGet httpGet = new HttpGet(url);
在进行请求时,httpGet作为参数执行execute,此时url是相对路径,httpclient会将defaulthost+uri拼接为完整的请求地址进行请求。
使用HttpClient进行http请求,每次请求随机使用一个target host进行请求。
发http请求的时候,一般会配置数据源,设置ClientPNames.DEFAULT_HOST,这样在请求的时候目标机器host和端口就是配置的ClientPNames.DEFAULT_HOST。但是不能每次请求ClientPNames.DEFAULT_HOST,因为一个httpclient就对应一个ClientPNames.DEFAULT_HOST,就无法针对一次request进行目标host的修改。
例如:
HttpGet httpGet = new HttpGet(url);
在进行请求时,httpGet作为参数执行execute,此时url是相对路径,httpclient会将defaulthost+uri拼接为完整的请求地址进行请求。
看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参数才能生效。