1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.IOException;
  4. import java.io.UnsupportedEncodingException;
  5. import java.security.KeyManagementException;
  6. import java.security.KeyStore;
  7. import java.security.KeyStoreException;
  8. import java.security.NoSuchAlgorithmException;
  9. import java.security.cert.CertificateException;
  10. import java.util.ArrayList;
  11. import java.util.List;
  12. import javax.net.ssl.SSLContext;
  13. import org.apache.http.HttpEntity;
  14. import org.apache.http.NameValuePair;
  15. import org.apache.http.ParseException;
  16. import org.apache.http.client.ClientProtocolException;
  17. import org.apache.http.client.entity.UrlEncodedFormEntity;
  18. import org.apache.http.client.methods.CloseableHttpResponse;
  19. import org.apache.http.client.methods.HttpGet;
  20. import org.apache.http.client.methods.HttpPost;
  21. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  22. import org.apache.http.conn.ssl.SSLContexts;
  23. import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
  24. import org.apache.http.entity.ContentType;
  25. import org.apache.http.entity.mime.MultipartEntityBuilder;
  26. import org.apache.http.entity.mime.content.FileBody;
  27. import org.apache.http.entity.mime.content.StringBody;
  28. import org.apache.http.impl.client.CloseableHttpClient;
  29. import org.apache.http.impl.client.HttpClients;
  30. import org.apache.http.message.BasicNameValuePair;
  31. import org.apache.http.util.EntityUtils;
  32. import org.junit.Test;
  33. public class HttpClientTest {
  34. @Test
  35. public void jUnitTest() {
  36. get();
  37. }
  38. /**
  39. * HttpClient连接SSL
  40. */
  41. public void ssl() {
  42. CloseableHttpClient httpclient = null;
  43. try {
  44. KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
  45. FileInputStream instream = new FileInputStream(new File("d:\\tomcat.keystore"));
  46. try {
  47. // 加载keyStore d:\\tomcat.keystore
  48. trustStore.load(instream, "123456".toCharArray());
  49. } catch (CertificateException e) {
  50. e.printStackTrace();
  51. } finally {
  52. try {
  53. instream.close();
  54. } catch (Exception ignore) {
  55. }
  56. }
  57. // 相信自己的CA和所有自签名的证书
  58. SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
  59. // 只允许使用TLSv1协议
  60. SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
  61. SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
  62. httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
  63. // 创建http请求(get方式)
  64. HttpGet httpget = new HttpGet("https://localhost:8443/myDemo/Ajax/serivceJ.action");
  65. System.out.println("executing request" + httpget.getRequestLine());
  66. CloseableHttpResponse response = httpclient.execute(httpget);
  67. try {
  68. HttpEntity entity = response.getEntity();
  69. System.out.println("----------------------------------------");
  70. System.out.println(response.getStatusLine());
  71. if (entity != null) {
  72. System.out.println("Response content length: " + entity.getContentLength());
  73. System.out.println(EntityUtils.toString(entity));
  74. EntityUtils.consume(entity);
  75. }
  76. } finally {
  77. response.close();
  78. }
  79. } catch (ParseException e) {
  80. e.printStackTrace();
  81. } catch (IOException e) {
  82. e.printStackTrace();
  83. } catch (KeyManagementException e) {
  84. e.printStackTrace();
  85. } catch (NoSuchAlgorithmException e) {
  86. e.printStackTrace();
  87. } catch (KeyStoreException e) {
  88. e.printStackTrace();
  89. } finally {
  90. if (httpclient != null) {
  91. try {
  92. httpclient.close();
  93. } catch (IOException e) {
  94. e.printStackTrace();
  95. }
  96. }
  97. }
  98. }
  99. /**
  100. * post方式提交表单(模拟用户登录请求)
  101. */
  102. public void postForm() {
  103. // 创建默认的httpClient实例.
  104. CloseableHttpClient httpclient = HttpClients.createDefault();
  105. // 创建httppost
  106. HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
  107. // 创建参数队列
  108. List<namevaluepair> formparams = new ArrayList<namevaluepair>();
  109. formparams.add(new BasicNameValuePair("username", "admin"));
  110. formparams.add(new BasicNameValuePair("password", "123456"));
  111. UrlEncodedFormEntity uefEntity;
  112. try {
  113. uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
  114. httppost.setEntity(uefEntity);
  115. System.out.println("executing request " + httppost.getURI());
  116. CloseableHttpResponse response = httpclient.execute(httppost);
  117. try {
  118. HttpEntity entity = response.getEntity();
  119. if (entity != null) {
  120. System.out.println("--------------------------------------");
  121. System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
  122. System.out.println("--------------------------------------");
  123. }
  124. } finally {
  125. response.close();
  126. }
  127. } catch (ClientProtocolException e) {
  128. e.printStackTrace();
  129. } catch (UnsupportedEncodingException e1) {
  130. e1.printStackTrace();
  131. } catch (IOException e) {
  132. e.printStackTrace();
  133. } finally {
  134. // 关闭连接,释放资源
  135. try {
  136. httpclient.close();
  137. } catch (IOException e) {
  138. e.printStackTrace();
  139. }
  140. }
  141. }
  142. /**
  143. * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
  144. */
  145. public void post() {
  146. // 创建默认的httpClient实例.
  147. CloseableHttpClient httpclient = HttpClients.createDefault();
  148. // 创建httppost
  149. HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
  150. // 创建参数队列
  151. List<namevaluepair> formparams = new ArrayList<namevaluepair>();
  152. formparams.add(new BasicNameValuePair("type", "house"));
  153. UrlEncodedFormEntity uefEntity;
  154. try {
  155. uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
  156. httppost.setEntity(uefEntity);
  157. System.out.println("executing request " + httppost.getURI());
  158. CloseableHttpResponse response = httpclient.execute(httppost);
  159. try {
  160. HttpEntity entity = response.getEntity();
  161. if (entity != null) {
  162. System.out.println("--------------------------------------");
  163. System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
  164. System.out.println("--------------------------------------");
  165. }
  166. } finally {
  167. response.close();
  168. }
  169. } catch (ClientProtocolException e) {
  170. e.printStackTrace();
  171. } catch (UnsupportedEncodingException e1) {
  172. e1.printStackTrace();
  173. } catch (IOException e) {
  174. e.printStackTrace();
  175. } finally {
  176. // 关闭连接,释放资源
  177. try {
  178. httpclient.close();
  179. } catch (IOException e) {
  180. e.printStackTrace();
  181. }
  182. }
  183. }
  184. /**
  185. * 发送 get请求
  186. */
  187. public void get() {
  188. CloseableHttpClient httpclient = HttpClients.createDefault();
  189. try {
  190. // 创建httpget.
  191. HttpGet httpget = new HttpGet("http://www.baidu.com/");
  192. System.out.println("executing request " + httpget.getURI());
  193. // 执行get请求.
  194. CloseableHttpResponse response = httpclient.execute(httpget);
  195. try {
  196. // 获取响应实体
  197. HttpEntity entity = response.getEntity();
  198. System.out.println("--------------------------------------");
  199. // 打印响应状态
  200. System.out.println(response.getStatusLine());
  201. if (entity != null) {
  202. // 打印响应内容长度
  203. System.out.println("Response content length: " + entity.getContentLength());
  204. // 打印响应内容
  205. System.out.println("Response content: " + EntityUtils.toString(entity));
  206. }
  207. System.out.println("------------------------------------");
  208. } finally {
  209. response.close();
  210. }
  211. } catch (ClientProtocolException e) {
  212. e.printStackTrace();
  213. } catch (ParseException e) {
  214. e.printStackTrace();
  215. } catch (IOException e) {
  216. e.printStackTrace();
  217. } finally {
  218. // 关闭连接,释放资源
  219. try {
  220. httpclient.close();
  221. } catch (IOException e) {
  222. e.printStackTrace();
  223. }
  224. }
  225. }
  226. /**
  227. * 上传文件
  228. */
  229. public void upload() {
  230. CloseableHttpClient httpclient = HttpClients.createDefault();
  231. try {
  232. HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceFile.action");
  233. FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));
  234. StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
  235. HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();
  236. httppost.setEntity(reqEntity);
  237. System.out.println("executing request " + httppost.getRequestLine());
  238. CloseableHttpResponse response = httpclient.execute(httppost);
  239. try {
  240. System.out.println("----------------------------------------");
  241. System.out.println(response.getStatusLine());
  242. HttpEntity resEntity = response.getEntity();
  243. if (resEntity != null) {
  244. System.out.println("Response content length: " + resEntity.getContentLength());
  245. }
  246. EntityUtils.consume(resEntity);
  247. } finally {
  248. response.close();
  249. }
  250. } catch (ClientProtocolException e) {
  251. e.printStackTrace();
  252. } catch (IOException e) {
  253. e.printStackTrace();
  254. } finally {
  255. try {
  256. httpclient.close();
  257. } catch (IOException e) {
  258. e.printStackTrace();
  259. }
  260. }
  261. }
  262. }

httpClient 入门实例的更多相关文章

  1. HttpClient入门

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

  2. React 入门实例教程(转载)

    本人转载自: React 入门实例教程

  3. struts入门实例

    入门实例 1  .下载struts-2.3.16.3-all  .不摆了.看哈就会下载了. 2  . 解压  后 找到 apps 文件夹. 3.    打开后将 struts2-blank.war   ...

  4. Vue.js2.0从入门到放弃---入门实例

    最近,vue.js越来越火.在这样的大浪潮下,我也开始进入vue的学习行列中,在网上也搜了很多教程,按着教程来做,也总会出现这样那样的问题(坑啊,由于网上那些教程都是Vue.js 1.x版本的,现在用 ...

  5. wxPython中文教程入门实例

    这篇文章主要为大家分享下python编程中有关wxPython的中文教程,分享一些wxPython入门实例,有需要的朋友参考下     wxPython中文教程入门实例 wx.Window 是一个基类 ...

  6. Omnet++ 4.0 入门实例教程

    http://blog.sina.com.cn/s/blog_8a2bb17d01018npf.html 在网上找到的一个讲解omnet++的实例, 是4.0下面实现的. 我在4.2上试了试,可以用. ...

  7. Spring中IoC的入门实例

    Spring中IoC的入门实例 Spring的模块化是很强的,各个功能模块都是独立的,我们可以选择的使用.这一章先从Spring的IoC开始.所谓IoC就是一个用XML来定义生成对象的模式,我们看看如 ...

  8. Node.js入门实例程序

    在使用Node.js创建实际“Hello, World!”应用程序之前,让我们看看Node.js的应用程序的部分.Node.js应用程序由以下三个重要组成部分: 导入需要模块: 我们使用require ...

  9. Java AIO 入门实例(转)

    Java7 AIO入门实例,首先是服务端实现: 服务端代码 SimpleServer: public class SimpleServer { public SimpleServer(int port ...

随机推荐

  1. 远程连接postgres,出现server doesnt listen

    已修改pg_hdb.conf中的 # IPv4 local connections:     host    all             all             127.0.0.1/32 ...

  2. Codevs 1380 没有上司的舞会

    时间限制: 1 s  空间限制: 128000 KB  题目等级 : 钻石 Diamond 题目描述 Description Ural大学有N个职员,编号为1~N.他们有从属关系,也就是说他们的关系就 ...

  3. Nginx在嵌入式系统中的应用

    -----------------本文转载自 http://blog.csdn.net/xteda/article/details/39708009 ------------------------- ...

  4. Python单元测试——深入理解unittest (转)

    单元测试的重要性就不多说了,可恶的是Python中 有太多的单元测试框架和工具,什么unittest, testtools, subunit, coverage, testrepository, no ...

  5. Ubuntu14.04忘记root密码的解决方法

    电脑20多天没用忘记密码了,下面是在网上找到的一个解决办法,其它的和这个也大概相同.因为其中有些缺漏,没能给我解决问题.通过分析最终问题还是解决了,现解决方案的关键点记录一下.希望能方便到其它人. 1 ...

  6. php foreach 操作数组的代码

    php foreach 操作数组的代码.   foreach()有两种用法:  foreach(array_name as $value)  {  statement;  }  这里的array_na ...

  7. js中的数组Array定义与sort方法使用示例

    Array的定义及sort方法使用示例 Array数组相当于java中的ArrayList  定义方法:  1:使用new Array(5  )创建数组 var ary = new Array(5): ...

  8. Python开发【第一篇】Python基础之函数递归

    函数递归 递归的本质: 就是一个函数调用另外一个函数. def d(): return '123' def c(): r = d() return r def b(): r = c() return ...

  9. [转]system函数返回值探究

    对于system这个函数的功能早就有一定了解,读书期间,就学习了UNIX系统编程这本书,后来买了APUE.我这个人总是有好读书不求甚解的毛病.对于system函数只知其一,不知其二.后来被人问起相关的 ...

  10. ASP.NET——拒绝访问。 (异常来自HRESULT:0x80070005 (E_ACCESSDENIED))

    运行ASP.NET网站的时候出现下面这个问题,这个问题如图: 这个问题的解决方法为: 运行dcomcnfg 点 组件服务->服务->电脑->我的电脑->DCOM 配置 找到&q ...