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. }

最新文章

  1. geotrellis使用(二十七)栅格数据色彩渲染
  2. PUTTY用密钥登陆服务器
  3. javafx之两种局部界面的呈现方式
  4. java web 相对路径中已/开头和不已/开头的区别
  5. js正则表达式入门
  6. 野比的示波器案例(Winfrom用户控件)
  7. Spring中@Component注解,@Controller注解详解
  8. .NET_RSA加密全接触(重、难点解析)
  9. android之Widget01
  10. Android 动画机制与使用技巧
  11. oracle 字符集
  12. 大四找实习(web前端),加油
  13. 使用Jquery.load()方法,出现-此页的状态信息无效,可能已损坏。[转]
  14. C/C++ ceil和floor函数
  15. TreeNode.trage的使用
  16. 163邮箱 SMTP发送邮件注意点
  17. appium 3 跑起来
  18. C++学习6-面向对象编程基础(运算符重载、类的派生与继承、命名空间)
  19. jQuery插件实践之轮播练习(一)
  20. oracle对日期date类型操作的函数

热门文章

  1. PHP 布尔类型
  2. (转)消息中间件的技术选型心得-RabbitMQ、ActiveMQ和ZeroMQ
  3. 8套迷人精致的CSS3 3D按钮动画
  4. Regionals 2013 :: North America - Southeast USA
  5. div+css3实现的小丸子和爷爷
  6. PHP 图片文件上传代码
  7. 左右滑动删除ListView条目Item--第三方开源--SwipeToDismiss
  8. Linq--扩展方法
  9. Linux驱动开发之开篇--HelloWorld
  10. 使用Qpython3制作老版天翼飞TP路由器拨号脚本