2 回答

TA貢獻(xiàn)1845條經(jīng)驗 獲得超8個贊
我遇到了同樣的問題,我通過使用LaxRedirectStrategy和覆蓋的 getRedirect方法解決了它。
顯然,當(dāng)初始重定向響應(yīng)不同于 307 或 308 時,POST 請求的默認(rèn)行為是將重定向調(diào)用作為 GET 請求。
請參閱: LaxRedirectStrategy 繼承自DefaultRedirectStrategy 。
在我的例子中,重定向響應(yīng)代碼是 302。
因此,如果您想要不同的東西,您可以重寫 getRedirect 方法并提供您自己的實現(xiàn)。
就像是:
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貢獻(xiàn)1799條經(jīng)驗 獲得超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);
}
}
})
添加回答
舉報