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
阅读全文
0 0
- httpclient post请求返回301解决方案
- HttpClient模拟Post请求返回Byte数组
- HttpClient的POST请求示例及返回接收
- HttpClient--HttpClient的Post请求
- Httpclient发送POST请求
- httpClient发送post请求
- HttpClient发起post请求
- HttpClient post 请求实例
- HttpClient发起POST请求
- httpclient Post请求
- httpclient post请求
- HttpClient Post请求
- httpclient post/set请求
- HttpClient发送post请求
- httpclient发送post请求
- httpClient post/get请求。
- httpClient post请求设置
- HttpClient get,Post请求
- RDD创建
- 列式存储的 parquet文件底层格式
- Happy Happy Prime Prime UVALive
- 那一年,我去了清华园,你去了阿里巴巴
- Java double的精度问题-BigDecimal的用法
- httpclient post请求返回301解决方案
- 初学c++ VS code + CMake 编译调试helloWord
- java基本线程机制
- 抱歉,老师讲得好不好,不是你们学生能评判得了的!
- 从RDD转换得到DataFrame
- select、poll、epoll 比较
- SqlServer数据库将单用户模式变成多用户模式的方法
- Java 判断一个点是否在一个三角形内
- String和StringBuffer区别