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

时间:2019-05-26 10:52:56

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

Am用托盘打到一个发布端点,但是它给出了错误302,当我在同一台服务器上尝试另一个get Url时,它给了我200。然后我使用LaxRedirectStrategy()重定向了发布请求,该发布请求被重定向到了get request(相同端点唯一的方法名称是GET和POST),它没有从post方法获取响应。谁能告诉我如何使用apahce httpClient 4.5

将发布请求重定向到发布请求
HttpClient client= HttpClientBuilder.create()
 .setRedirectStrategy(new LaxRedirectStrategy()).build();
HttpPost post = new HttpPost("url");
post.addHeader("content-type", " application/json");
HttpResponse response = client.execute(post);

2 个答案:

答案 0 :(得分:1)

我遇到了同样的问题,可以通过将 LaxRedirectStrategy 与覆盖的 getRedirect 方法一起使用来解决。

显然,POST请求的默认行为是,当初始重定向响应不同于307或308时,将重定向调用作为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);
                }
            }
        }
    }

答案 1 :(得分:1)

$color ="red";
$no = 0;
// echo "<pre>"; print_r($instock_products);
if(!empty($instock_products)){
foreach ($instock_products as $row) {
if($row->product_id<15){$color="pink";}
elif($row->date < 2022-03-15){$color="green";}
elif($row->product_id<15 ||$row->date < 2022-03-15 ){$color="blue";}

?>

<tr class="gradeA" style="background-color:<?php echo $color; ?>">
DISPLAY YOUR DATA HERE

</tr>