2 回答
TA贡献1845条经验 获得超8个赞
我遇到了同样的问题,我通过使用LaxRedirectStrategy和覆盖的 getRedirect方法解决了它。
显然,当初始重定向响应不同于 307 或 308 时,POST 请求的默认行为是将重定向调用作为 GET 请求。
请参阅: LaxRedirectStrategy 继承自DefaultRedirectStrategy 。
在我的例子中,重定向响应代码是 302。
因此,如果您想要不同的东西,您可以重写 getRedirect 方法并提供您自己的实现。
就像是:
new LaxRedirectStrategy() {
@Override
public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, 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 {
final int status = response.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_TEMPORARY_REDIRECT || status == HttpStatus.SC_MOVED_TEMPORARILY) { //HttpStatus.SC_MOVED_TEMPORARILY == 302
return RequestBuilder.copy(request).setUri(uri).build();
} else {
return new HttpGet(uri);
}
}
}
}
TA贡献1799条经验 获得超9个赞
HttpClient httpClient =
HttpClients.custom().setRedirectStrategy(new LaxRedirectStrategy() {
/*
* (non-Javadoc)
*
* @see org.apache.http.impl.client.DefaultRedirectStrategy#
* getRedirect(org.apache.http.HttpRequest,
* org.apache.http.HttpResponse,
* org.apache.http.protocol.HttpContext)
*/
@Override
public HttpUriRequest getRedirect(
HttpRequest request, HttpResponse response,
HttpContext context) throws ProtocolException
{
final URI uri = getLocationURI(request, response, context);
final String method = request.getRequestLine().getMethod();
if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
HttpPost post = new HttpPost(uri);
post.setEntity(entity);
return post;
} else if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) {
return new HttpHead(uri);
} else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) {
return new HttpGet(uri);
} else {
final int status =
response.getStatusLine().getStatusCode();
return status == HttpStatus.SC_TEMPORARY_REDIRECT
? RequestBuilder.copy(request).setUri(uri).build()
: new HttpGet(uri);
}
}
})
添加回答
举报