java - Apache HttpClient 4.5 将 POST 请求重定向到 GET 请求

标签 java spring-boot apache-httpclient-4.x

我正在尝试命中一个 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/

相关文章:

java - 为什么我能够在 Long 中存储比允许的更大的值? java

java - 使用 Java 参数化类型和多态性实现这种通用编程场景的方法

java - 无法执行目标 org.apache.maven.plugins :maven-compiler-plugin:3. 8.1:compile (default-compile) on project fhirql: Fatal error compiler

java - Hoverfly仿真模式在单元测试中与Spring Cloud Config Server冲突

java - 如何跳过 block 中的任何错误并继续下一个 block 项目?

java - 使用 HttpAsyncClient 发送异步调用时出现问题

java - 与 EJB 的远程连接在本地主机上工作,但在 127.0.0.1 和另一台服务器上失败

java - 如何移动矩阵中的元素组?

java - apache httpclient + ntlm 身份验证

java - HttpClient javax.net.ssl.SSLPeerUnverifiedException : peer not authenticated when time shifted?