}
/** {@inheritDoc} */
public HttpResponse fetch(HttpRequest request) {
HttpClient httpClient = new HttpClient();
HttpMethod httpMethod;
String methodType = request.getMethod();
String requestUri = request.getUri().toString();
// Select a proxy based on the URI. May be Proxy.NO_PROXY
Proxy proxy = ProxySelector.getDefault().select(request.getUri().toJavaUri()).get(0);
if (proxy != Proxy.NO_PROXY) {
InetSocketAddress address = (InetSocketAddress) proxy.address();
httpClient.getHostConfiguration().setProxy(address.getHostName(), address.getPort());
}
if ("POST".equals(methodType) || "PUT".equals(methodType)) {
EntityEnclosingMethod enclosingMethod = ("POST".equals(methodType))
? new PostMethod(requestUri)
: new PutMethod(requestUri);
if (request.getPostBodyLength() > 0) {
enclosingMethod.setRequestEntity(new InputStreamRequestEntity(request.getPostBody()));
enclosingMethod.setRequestHeader("Content-Length",
String.valueOf(request.getPostBodyLength()));
}
httpMethod = enclosingMethod;
} else if ("DELETE".equals(methodType)) {
httpMethod = new DeleteMethod(requestUri);
} else {
httpMethod = new GetMethod(requestUri);
}
httpMethod.setFollowRedirects(false);
httpMethod.getParams().setSoTimeout(connectionTimeoutMs);
httpMethod.setRequestHeader("Accept-Encoding", "gzip, deflate");
for (Map.Entry<String, List<String>> entry : request.getHeaders().entrySet()) {
httpMethod.setRequestHeader(entry.getKey(), StringUtils.join(entry.getValue(), ','));
}
try {
int statusCode = httpClient.executeMethod(httpMethod);
// Handle redirects manually
if (request.getFollowRedirects() &&
((statusCode == HttpStatus.SC_MOVED_TEMPORARILY) ||
(statusCode == HttpStatus.SC_MOVED_PERMANENTLY) ||
(statusCode == HttpStatus.SC_SEE_OTHER) ||
(statusCode == HttpStatus.SC_TEMPORARY_REDIRECT))) {
Header header = httpMethod.getResponseHeader("location");
if (header != null) {
String redirectUri = header.getValue();
if ((redirectUri == null) || (redirectUri.equals(""))) {
redirectUri = "/";
}
httpMethod.releaseConnection();
httpMethod = new GetMethod(redirectUri);
statusCode = httpClient.executeMethod(httpMethod);
}
}
return makeResponse(httpMethod, statusCode);
} catch (IOException e) {
if (e instanceof java.net.SocketTimeoutException ||
e instanceof java.net.SocketException) {
return HttpResponse.timeout();
}
return HttpResponse.error();
} finally {
httpMethod.releaseConnection();
}
}