HttpClientUtils
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpClientUtils {
private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);
private static final String ENCODING = "utf-8";
/**
* 发送 get请求
*/
public static String get(String url,String encoding,String headerKeyValue) {
encoding = null == encoding ? ENCODING : encoding;
CloseableHttpClient httpclient = HttpClients.createDefault();
String responseStr = null;
try {
// 创建httpget.
HttpGet httpget = new HttpGet(url);
if(!StringUtils.isEmpty(headerKeyValue)){
String[] headerKeyValueArr = headerKeyValue.split(";");
for (String keyValue : headerKeyValueArr) {
String[] KeyValueArr = keyValue.split("=");
if("Content-Type".equals(KeyValueArr[0]))
httpget.addHeader(KeyValueArr[0], KeyValueArr[1]+";charset="+encoding);
else
httpget.addHeader(KeyValueArr[0], KeyValueArr[1]);
}
}
logger.info("executing request :" + httpget.getURI());
// 执行get请求.
CloseableHttpResponse response = httpclient.execute(httpget);
// 打印响应状态
System.out.println("-------- :"+response.getStatusLine());
int responseCode = response.getStatusLine().getStatusCode();
if(responseCode != 200 ) return responseStr;
// 获取响应实体
HttpEntity entity = response.getEntity();
if (entity == null) return responseStr;
responseStr = EntityUtils.toString(entity,encoding);
// 打印响应内容长度
logger.info("Response content length: " + entity.getContentLength());
// 打印响应内容
logger.info("Response content: " +responseStr );
return responseStr;
} catch (ClientProtocolException e) {
logger.error("........httpget request error : " + e);
e.printStackTrace();
} catch (ParseException ee) {
logger.error("........httpget request error : " + ee);
ee.printStackTrace();
} catch (IOException eee) {
logger.error("........httpget request error : " + eee);
eee.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return responseStr;
}
/**
* 发送 post请求
*/
public static String post(String url ,List<NameValuePair> params,String encoding,String headerKeyValue) {
encoding = null == encoding ? ENCODING : encoding;
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
String responseStr = null;
try {
// 创建httppost
HttpPost httppost = new HttpPost(url);
if(!StringUtils.isEmpty(headerKeyValue)){
String[] headerKeyValueArr = headerKeyValue.split(";");
for (String keyValue : headerKeyValueArr) {
String[] KeyValueArr = keyValue.split("=");
if("Content-Type".equals(KeyValueArr[0]))
httppost.addHeader(KeyValueArr[0], KeyValueArr[1]+";charset="+encoding);
else
httppost.addHeader(KeyValueArr[0], KeyValueArr[1]);
}
}
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(params, encoding);
httppost.setEntity(uefEntity);
logger.info("executing request :" + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
// 打印响应状态
System.out.println("-------- :"+response.getStatusLine());
int responseCode = response.getStatusLine().getStatusCode();
if(responseCode != 200 ) return responseStr;
HttpEntity entity = response.getEntity();
if (entity == null) return responseStr;
responseStr = EntityUtils.toString(entity, encoding);
logger.info("Response content : " + responseStr);
return responseStr;
} catch (ClientProtocolException e) {
logger.error("........httppost request error : " + e);
e.printStackTrace();
} catch (UnsupportedEncodingException ee) {
logger.error("........httppost request error : " + ee);
ee.printStackTrace();
} catch (IOException eee) {
logger.error("........httppost request error : " + eee);
eee.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return responseStr;
}
}
HttpClientUtils的更多相关文章
- HttpClientUtils.java
package com.vcredit.ddcash.batch.util; import java.io.BufferedReader;import java.io.ByteArrayOutputS ...
- 包括post,get请求(http,https)的HttpClientUtils
package cn.knet.data.untils; import java.io.IOException; import java.net.SocketTimeoutException; imp ...
- 简单HttpClientUtils工具类
package com.zy.utils; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import o ...
- Web 开发工具类(2): HttpClientUtils
HttpClientUtils 整合了一些 web开发中常用的httpClient操作: package com.evan.common.utils; import java.io.IOExcepti ...
- coding++ :HttpClientUtils 封装
1.关键 JAR <!-- <<===================>> httpClient <<===================>> ...
- HttpClientUtils:Http请求工具类
HttpClientUtils:Http请求工具类 Scala:HttpClientUtils Scala:HttpClientUtils import java.io.IOException imp ...
- 强大的httpClientUtils
<!-- https://mvnrepository.com/artifact/com.arronlong/httpclientutil --> <dependency> &l ...
- Restful 介绍及SpringMVC+restful 实例讲解
restful不是一个框架,称为一种编码更烦更贴切吧,其核心类位于spring-web.jar中,即RestTemplate.class restful是rpc通过http协议的一种实现方式,和web ...
- 【tomcat】HTTPS访问配置 + restful调用远程HTTPS绕过验证
单向验证: 第一步: 生成key: keytool -genkey -alias mykey -keyalg RSA -keystore d:/key/testkey keytool -export ...
随机推荐
- JavaScriptPolyfillShim 在JavaScript中Shim和Polyfill有什么区别?
在JavaScript的世界里,有两个词经常被提到,那就是Shim和Polyfill,它们指的都是什么,又有什么区别?在本文中,将简短的给大家介绍他们之间的联系和区别.Shim一个shim就是一个库, ...
- requests高级用法
会话对象 当你向同一主机发送多个请求时,session会重用底层的tcp连接,从而提升性能,同时session也会为所有请求保持 cookie. # _*_ coding: utf-8 _*_ imp ...
- FCN网络的训练——以SIFT-Flow 数据集为例
参考文章: http://blog.csdn.net/u013059662/article/details/52770198 caffe的安装配置,以及fcn的使用在我前边的文章当中都已经提及到了,这 ...
- out.print()和response.getWriter().write()区别
1.print()和write()区别: write():表示的是仅支持输入字符类型数据,字符,字符数组和字符串等, print():表示的是将各种数据类型(包括object)的数据通过默认编码换成b ...
- VirtualBox后台运行虚拟机(无图形界面启动虚拟机)
有时候可能会用虚拟机搭建集群,这是通常希望不现实图形界面,试了半天,似乎只有Virtual Box支持无图形界面运行虚拟机,方法如下: 在Virtual Box的安装目录中找到VBoxManage,M ...
- highchart 中数据千分位显示为空格而不是逗号的解决方案
thousandsSep: String 一千的分隔符 在highcharts.js 中找到 thousandsSep位置,把"" 改为 ","
- Javascript 技巧集(1)
1. 数组克隆, 使用 slice() 方法 var a1 = [1,2,3,4]; var a2 = a1.slice(); 2. 强制将变量值转化为 bool 类型,前置双感叹号 !! var a ...
- 扩展ValidationAttribute 1
MVC中经常会用一些服务端对Model的验证. 服务端验证要继承自ValidationAttribute,并重写IsValid虚方法来自定义自己的验证规则. protected override Va ...
- web api 开发记录
1. 修改 api 返回时间格式 //配置返回的时间类型数据格式 GlobalConfiguration.Configuration.Formatters.JsonFormatter.Serializ ...
- Win+R命令大全
explorer---------------------打开资源管理器logoff------------------------注销命令lusrmgr.msc----------------本机用 ...