我正在尝试命中一个 post 端点,但它给出了错误 302,当我在同一服务器上尝试另一个 get Url 时,它给了我 200。然后我使用 LaxRedirectStrategy() 重定向了 post 请求,post 请求正在重定向到 get请求(同一端点仅方法名称为 GET 和 POST)它没有从 post 方法获取响应。谁能告诉我如何使用 apahce httpClient 4.5 将 post 请求重定向到 post 请求
HttpClient client= HttpClientBuilder.create()
.setRedirectStrategy(new LaxRedirectStrategy()).build();
HttpPost post = new HttpPost("url");
post.addHeader("content-type", " application/json");
HttpResponse response = client.execute(post);
最佳答案
我遇到了同样的问题,我通过使用 LaxRedirectStrategy 和重写的 getRedirect 方法解决了这个问题。
显然,当初始重定向响应不同于 307 或 308 时,POST 请求的默认行为是将重定向调用作为 GET 请求进行。
参见: DefaultRedirectStrategy LaxRedirectStrategy 继承自其中。
在我的例子中,重定向响应代码是 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);
}
}
}
}
关于java - Apache HttpClient 4.5 将 POST 请求重定向到 GET 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56312858/