httpclient post请求返回301解决方案

本文介绍了一种解决HTTP POST请求遇到301重定向问题的方法。当使用HttpClient进行POST请求并遇到301状态码时,可以通过设置LaxRedirectStrategy策略来解决。文章提供了具体的代码实现及解决方案链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 public static String post(String url, Map<String,Object> paramMap,Map<String,String> headerMap) {
        CloseableHttpClient httpClient = HttpClients.createDefault();

        try {
            HttpPost post = new HttpPost(url);


            //请求头
            if(headerMap != null){
                for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                    post.addHeader(entry.getKey(),entry.getValue());
                }
            }

            //创建参数列表
            List<NameValuePair> nameValuePairs = Lists.newArrayList();
            for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
                if(entry.getValue() instanceof String) {
                    nameValuePairs.add(new BasicNameValuePair(entry.getKey(), (String) entry.getValue()));
                }else if(entry.getValue() instanceof String[]){
                    String[] arr = (String[]) entry.getValue();
                    for(String val : arr){
                        nameValuePairs.add(new BasicNameValuePair(entry.getKey(), val));
                    }
                }
            }
            //url格式编码
            UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(nameValuePairs,"UTF-8");
            post.setEntity(uefEntity);
            //执行请求
            CloseableHttpResponse httpResponse = httpClient.execute(post);
            if(httpResponse.getStatusLine() == null || httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK){
                return "";
            }
            try{
                HttpEntity entity = httpResponse.getEntity();
                if (null != entity){
                    return EntityUtils.toString(entity);

                }
            } finally{
                httpResponse.close();
            }

        } catch( UnsupportedEncodingException e){
            LOGGER.error("连接异常",e);
            return "";
        } catch (IOException e) {
            LOGGER.error("连接异常",e);
            return "";
        }
        finally{
            if (httpClient != null){
                try {
                    httpClient.close();
                } catch (IOException e) {
                    LOGGER.error("连接异常",e);
                }
            }
        }

        return "";
    }

如上代码,状态码返回301,httpclient版本为4.0以上版本,查了很久,答案都略坑,最后找到解决办法是将httpclient的创建方式改为如下代码:

        CloseableHttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();

附解决方案地址:http://www.baeldung.com/httpclient-redirect-on-http-post

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值