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. 多个相同script引用探索

    1.页面直接就有,或者document.write页面加载同步输出 其实就是当script是页面初始加载的一部分的情况,script是同步的,只有在上一个加载并执行完才会进行下一个script加载. ...

  2. linux install mpi4py

    Downloading The MPI for Python package is available for download at the project website generously h ...

  3. 转载:Linux内核探索之路——关于书

    转自http://blog.chinaunix.net/uid-20608849-id-3029223.html 在学习Linux内核代码的过程中,定会参考很多书籍以及网路资源,但是并不是所有的书籍和 ...

  4. C++ const用法小结 (欢迎大家拍砖)

    C++const 关键字小结 const 是constant的缩写,本意是不变的,不易改变的意思. const 在C++中是用来修饰内置类型变量,自定义对象,成员函数,返回值,函数参数. 一.cons ...

  5. Java包的命名规则

    按照惯例,包申明遵循特定的格式.虽然不是严格要求的Java语法,如果不遵循格式要求,大多数的Java认为你是不懂Java. 从右到左的顺序是: 1.systaxExample表明包的本地名称. 2.e ...

  6. System.Data.OracleClient 需要 Oracle 客户端软件 version 8.1.7 或更高版本

    说明: 执行当前 Web 请求期间,出现未经处理的异常.请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息. 异常详细信息: System.ServiceModel.FaultEx ...

  7. Android实现发短信与打电话的功能

    //发短信 class SendMsgClickListener implements OnClickListener { public void onClick(View v) { //调用Andr ...

  8. MySQL实战积累

    IFNULL(expr1,expr2)的用法:假如expr1不为NULL,则IFNULL()的返回值为   expr1; 否则其返回值为expr2. 索引:http://www.cnblogs.com ...

  9. BI的核心价值[转]

    BI的核心价值是辅助决策,从一个洁净的数据源中自动提取有价值的数据进行分析,从而成为重要商业决定的决策基础.但在国内,洁净的数据源不易得到,很多情况下都需要进行数据清洗,所以BI的应用受到很大程度的抑 ...

  10. 【nodejs】关于 alert 和 document

    Microsoft Windows [版本 6.1.7601] 版权所有 (c) 2009 Microsoft Corporation.保留所有权利. C:\Windows\system32>n ...