httpclient post请求返回301解决方案

来源:互联网 发布:上下课铃声软件 编辑:程序博客网 时间:2024/05/17 03:28
 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

原创粉丝点击