我正在使用Apache HttpComponents连接到另一个公司的API。
该公司服务器正在将我的POST请求重定向到另一个位置,因此我必须配置HttpComponents以允许循环重定向:
private RequestConfig defaultRequestConfig = RequestConfig.custom()
.setCookieSpec(CookieSpecs.DEFAULT)
.setCircularRedirectsAllowed(true)
.build();
private CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultRequestConfig(defaultRequestConfig)
.setRedirectStrategy(CustomRedirectStrategy.INSTANCE)
.build();
GET请求工作正常,但是当我尝试POST时,HttpComponents似乎忽略了我尝试发送的正文。波纹管是我用于POST的代码,也是HttpComponents生成的(恢复的)日志:
public CloseableHttpResponse doPOST(String url, String stringEntity) throws IOException {
HttpPost request = new HttpPost(url);
request.setEntity(new StringEntity(stringEntity));
request.setHeader("Accept", "application/json;");
request.setHeader("Content-type", "application/json;");
return httpclient.execute(request);
}
-> POST (http://some-server.com/api/test) (Content-Length: 65)
<- 302 (https://some-server.com/api/test)
-> POST (https://some-server.com/api/test) (Content-Length: 0)
<- 302 (http://some-server.com/api/test)
-> POST (http://some-server.com/api/test) (Content-Length: 0)
<- 302 (https://some-server.com/api/test)
-> POST (https://some-server.com/api/test) (Content-Length: 0)
<- 404 (Not Found)
->
适用于我发送的邮件,<-
适用于收到的邮件
我看到第一个POST的Content-Length为65,但是重定向后的POST没有。
重定向后,HttpComponents是否忽略了我的POST实体?如果是这样,我如何配置它甚至在重定向时也可以发送此数据?
不好。CustomRedirectStrategy
是我创建的一个类,它从LaxRedirectStrategy
扩展并覆盖#getRedirect
以将POST方法重定向到POST而不是GET。
答案 0 :(得分:0)
要将数据从原始POST重新发布到重定向,我们可以实施特定的重定向策略,以覆盖#getRedirect
:
@Contract(threading = ThreadingBehavior.IMMUTABLE)
public class CustomRedirectStrategy extends LaxRedirectStrategy {
public static final CustomRedirectStrategy INSTANCE = new CustomRedirectStrategy();
@Override
public HttpUriRequest getRedirect(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws ProtocolException {
final URI uri = getLocationURI(request, response, context);
final String method = request.getRequestLine().getMethod();
if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) {
return new HttpHead(uri);
} else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) {
return new HttpGet(uri);
} else if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
return RequestBuilder.copy(request).setUri(uri).build(); // Here
} else {
final int status = response.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_TEMPORARY_REDIRECT) {
return RequestBuilder.copy(request).setUri(uri).build();
} else {
return new HttpGet(uri);
}
}
}
}
对于POST方法,请基于原始请求返回一个请求。
要使其正常工作,您必须在HttpClient
实例上设置此重定向策略:
public CloseableHttpClient getHttpClient() {
return HttpClients.custom()
.setDefaultRequestConfig(defaultRequestConfig)
.setRedirectStrategy(CustomRedirectStrategy.INSTANCE) // Here
.build();
}