HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可:

  1. 创建CloseableHttpClient对象。
  2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
  3. 如果需要发送请求参数,可可调用setEntity(HttpEntity entity)方法来设置请求参数。setParams方法已过时(4.4.1版本)。
  4. 调用HttpGet、HttpPost对象的setHeader(String name, String value)方法设置header信息,或者调用setHeaders(Header[] headers)设置一组header信息。
  5. 调用CloseableHttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个CloseableHttpResponse。
  6. 调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容;调用CloseableHttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头。
  7. 释放连接。无论执行方法是否成功,都必须释放连接

具体代码如下(HttpClient-4.4.1):

/**
* 简单httpclient实例
*
* @author arron
* @date 2015年11月11日 下午6:36:49
* @version 1.0
*/
public class SimpleHttpClientDemo { /**
* 模拟请求
*
* @param url 资源地址
* @param map 参数列表
* @param encoding 编码
* @return
* @throws ParseException
* @throws IOException
*/
public static String send(String url, Map<String,String> map,String encoding) throws ParseException, IOException{
String body = ""; //创建httpclient对象
CloseableHttpClient client = HttpClients.createDefault();
//创建post方式请求对象
HttpPost httpPost = new HttpPost(url); //装填参数
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
if(map!=null){
for (Entry<String, String> entry : map.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
//设置参数到请求对象中
httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding)); System.out.println("请求地址:"+url);
System.out.println("请求参数:"+nvps.toString()); //设置header信息
//指定报文头【Content-type】、【User-Agent】
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //执行请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse response = client.execute(httpPost);
//获取结果实体
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, encoding);
}
EntityUtils.consume(entity);
//释放链接
response.close();
return body;
}
}

对于HTTPS的访问,采取绕过证书的策略:

    /**
* 绕过验证
*
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sc = SSLContext.getInstance("SSLv3"); // 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
X509TrustManager trustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
} @Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
} @Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
}; sc.init(null, new TrustManager[] { trustManager }, null);
return sc;
}

然后修改原来的send方法:

    /**
* 模拟请求
*
* @param url 资源地址
* @param map 参数列表
* @param encoding 编码
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws IOException
* @throws ClientProtocolException
*/
public static String send(String url, Map<String,String> map,String encoding) throws KeyManagementException, NoSuchAlgorithmException, ClientProtocolException, IOException {
String body = "";
//采用绕过验证的方式处理https请求
SSLContext sslcontext = createIgnoreVerifySSL(); // 设置协议http和https对应的处理socket链接工厂的对象
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext))
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
HttpClients.custom().setConnectionManager(connManager); //创建自定义的httpclient对象
CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
// CloseableHttpClient client = HttpClients.createDefault(); //创建post方式请求对象
HttpPost httpPost = new HttpPost(url); //装填参数
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
if(map!=null){
for (Entry<String, String> entry : map.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
//设置参数到请求对象中
httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding)); System.out.println("请求地址:"+url);
System.out.println("请求参数:"+nvps.toString()); //设置header信息
//指定报文头【Content-type】、【User-Agent】
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //执行请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse response = client.execute(httpPost);
//获取结果实体
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, encoding);
}
EntityUtils.consume(entity);
//释放链接
response.close();
return body;
}

但是,如果是自己用jdk或者其他工具生成的证书,还是希望用其他方式认证自签名的证书,这篇文章就来分享一下如何设置信任自签名的证书。当然你也可以参考官网示例中。

要想信任自签名的证书,必须得知道密钥库的路径及密钥库的密码。然后加载到程序来才可以。具体代码如下:

    /**
* 设置信任自签名证书
*
* @param keyStorePath 密钥库路径
* @param keyStorepass 密钥库密码
* @return
*/
public static SSLContext custom(String keyStorePath, String keyStorepass){
SSLContext sc = null;
FileInputStream instream = null;
KeyStore trustStore = null;
try {
trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
instream = new FileInputStream(new File(keyStorePath));
trustStore.load(instream, keyStorepass.toCharArray());
// 相信自己的CA和所有自签名的证书
sc = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
} catch (KeyStoreException | NoSuchAlgorithmException| CertificateException | IOException | KeyManagementException e) {
e.printStackTrace();
} finally {
try {
instream.close();
} catch (IOException e) {
}
}
return sc;
}

然后修改原来的send方法:

    /**
* 模拟请求
*
* @param url 资源地址
* @param map 参数列表
* @param encoding 编码
* @return
* @throws ParseException
* @throws IOException
* @throws KeyManagementException
* @throws NoSuchAlgorithmException
* @throws ClientProtocolException
*/
public static String send(String url, Map<String,String> map,String encoding) throws ClientProtocolException, IOException {
String body = ""; //tomcat是我自己的密钥库的密码,你可以替换成自己的
//如果密码为空,则用"nopassword"代替
SSLContext sslcontext = custom("D:\\keys\\wsriakey", "tomcat"); // 设置协议http和https对应的处理socket链接工厂的对象
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext))
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
HttpClients.custom().setConnectionManager(connManager); //创建自定义的httpclient对象
CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
// CloseableHttpClient client = HttpClients.createDefault(); //创建post方式请求对象
HttpPost httpPost = new HttpPost(url); //装填参数
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
if(map!=null){
for (Entry<String, String> entry : map.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
//设置参数到请求对象中
httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding)); System.out.println("请求地址:"+url);
System.out.println("请求参数:"+nvps.toString()); //设置header信息
//指定报文头【Content-type】、【User-Agent】
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //执行请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse response = client.execute(httpPost);
//获取结果实体
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, encoding);
}
EntityUtils.consume(entity);
//释放链接
response.close();
return body;
}

HttpClient中post请求http、https示例的更多相关文章

  1. httpclient 中post请求重定向

    背景:使用httpclient 的post请求进行登录,需要重定向登录,请求重定向后的地址 在httpclient中post请求不像get请求自己可以重定向,实现方式是 判断post请求返回码是否是3 ...

  2. JAVA HttpClient进行POST请求(HTTPS)

    目前,要为另一个项目提供接口,接口是用HTTP URL实现的,最初的想法是另一个项目用jQuery post进行请求. 但是,很可能另一个项目是部署在别的机器上,那么就存在跨域问题,而jquery的p ...

  3. JAVA利用HttpClient进行POST请求(HTTPS)

    目前,要为另一个项目提供接口,接口是用HTTP URL实现的,最初的想法是另一个项目用jQuery post进行请求. 但是,很可能另一个项目是部署在别的机器上,那么就存在跨域问题,而JQuery的p ...

  4. 封装HttpClient进行http请求与https请求

    一.https忽略证书 /** * 用于进行Https请求的HttpClient * * @author joey * */ public class SSLClient { public stati ...

  5. LR中常见请求的使用示例

    Action(){ //application/x-www-form-urlencoded //application/json //web_add_auto_header("Content ...

  6. C# 应用 - 使用 HttpClient 发起 Http 请求

    1. 需要的库类 \Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Net.Http.dll System.N ...

  7. C#中用HttpWebRequest中发送GET/HTTP/HTTPS请求 (转载)

    这个需求来自于我最近练手的一个项目,在项目中我需要将一些自己发表的和收藏整理的网文集中到一个地方存放,如果全部采用手工操作工作量大而且繁琐,因此周公决定利用C#来实现.在很多地方都需要验证用户身份才可 ...

  8. 在C#用HttpWebRequest中发送GET/HTTP/HTTPS请求

    通用辅助类  下面是我编写的一个辅助类,在这个类中采用了HttpWebRequest中发送GET/HTTP/HTTPS请求,因为有的时候需 要获取认证信息(如Cookie),所以返回的是HttpWeb ...

  9. (转) 在C#用HttpWebRequest中发送GET/HTTP/HTTPS请求

    转自:http://blog.csdn.net/zhoufoxcn/article/details/6404236 通用辅助类 下面是我编写的一个辅助类,在这个类中采用了HttpWebRequest中 ...

随机推荐

  1. 进程显示,删除,调度 ps, top kill

    ps:查看进程的情况,显示的是某一时间进程的运行状态.ps --help top:也是查看进程的情况,动态显示进程信息! kill:杀死进程的情况, sudo kill --help 查看相关参数 c ...

  2. CentOS使用sudo提示用户不在sudoers文件中的解决方法

    1切换到root用户[linux@localhost ~]$ su root密码:[root@localhost ~]# 2查看/etc/sudoers文件权限,如果只读权限,修改为可写权限 [roo ...

  3. MVC + JQUERY + AJAX

  4. C#——System.Diagnostics.Process.Start的妙用

    我们经常会遇到在Winform或是WPF中点击链接或按钮打开某个指定的网址, 或者是需要打开电脑中某个指定的硬盘分区及文件夹, 甚至是"控制面板"相关的东西, 那么如何做呢? 答案 ...

  5. 【C语言】中的布尔类型

    C语言中的布尔类型 一.相关基础知识 首先bool  true  false为C++中的关键字,C语言中默认不支持这几个字符! 二.具体内容 在C89 (ANSI C)标准中没有定义与布尔类型相关的内 ...

  6. 类集对enum的支持。

    1,EmumMap public class EnumMap<K extends Enum<K>,V>extends AbstractMap<K,V>impleme ...

  7. Windows server2008 搭建ASP接口访问连接oracle数据库全过程记录--备用

    真的是太不容易了,以前的时候在window server 2003上面搭建了一套asp+oracle的接口系统,就费了好大的劲儿,其实那会迷迷瞪瞪的也不知道怎么的就弄好了,也懒得管了.OK,从昨天到今 ...

  8. Eclipse右键New菜单项的自定义设置

    大家都知道一般在Eclipse中新建一个项目或者文件都是通过菜单项的File-New来创建,然而有些右键出来的选项可能从来都不会使用到,而有些可能会常用到但是右键中又没有,这个时候就可以自定义New中 ...

  9. apache整合tomcat部署集群

    近日,由于公司项目需要,所以学习了apache整合tomcat以及集群的一些知识. 所以做下笔记日后回顾可以用到. apache只有处理静态事物的能力, 而tomcat的强项就是处理动态的请求,所以a ...

  10. [wikioi]没有上司的舞会

    树形DP.用F[k][0]和F[k][1]表示某节点不选和选了之后子树的最大值.那么:f[i][0]=sigma(max(f[k][0],f[k][1]))f[i][1]=sigma(f[k][0]) ...