1.场景描述

  使用Apache开源组织中的HttpComponents,完成对http服务器的访问功能,消息体xml报文。

2.HttpComponents项目的介绍

  HttpComponents项目就是专门设计来简化HTTP客户端与服务器进行各种通讯编程。通过它可以让原来很头疼的事情现在轻松的解决,例如你不再管是HTTP或者HTTPS的通讯方式,告诉它你想使用HTTPS方式,剩下的事情交给 httpclient替你完成。

3.maven依赖 

  1. <dependency>
  2. <groupId>org.apache.httpcomponents</groupId>
  3. <artifactId>httpclient</artifactId>
  4. <version>4.3.1</version>
  5. </dependency>

4.代码编写

工具类

  1. import org.apache.http.HttpEntity;
  2. import org.apache.http.HttpHeaders;
  3. import org.apache.http.client.config.RequestConfig;
  4. import org.apache.http.client.methods.CloseableHttpResponse;
  5. import org.apache.http.client.methods.HttpGet;
  6. import org.apache.http.client.methods.HttpPost;
  7. import org.apache.http.client.methods.HttpUriRequest;
  8. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  9. import org.apache.http.entity.StringEntity;
  10. import org.apache.http.impl.client.CloseableHttpClient;
  11. import org.apache.http.impl.client.HttpClients;
  12. import org.apache.http.util.EntityUtils;
  13.  
  14. import javax.net.ssl.KeyManager;
  15. import javax.net.ssl.SSLContext;
  16. import javax.net.ssl.TrustManager;
  17. import javax.net.ssl.X509TrustManager;
  18. import java.io.IOException;
  19. import java.security.SecureRandom;
  20. import java.security.cert.CertificateException;
  21. import java.security.cert.X509Certificate;
  22.  
  23. /**
  24. * apache httpclient 工具类
  25. * 支持对 http https 接口调用
  26. * <P>
  27. * 1.GET 请求
  28. * 2.POST 请求
  29. * </P>
  30. */
  31. public class HttpDelegate {
  32. private int timeOut = 10000;//指定超时时间
  33. private CloseableHttpClient httpClient;
  34. private RequestConfig requestConfig;//设置请求参数
  35.  
  36. /**
  37. * 对象被创建时执行
  38. */
  39. public HttpDelegate(Boolean isHttps){
  40. httpClient = this.getHttpClient(isHttps);
  41. this.initRequestConfig();//初始化请求配置
  42. }
  43.  
  44. /**
  45. * 发送post请求
  46. * @param url 请求地址
  47. * @param contentType 请求类型
  48. * @param encoding 编码格式
  49. * @param param 请求参数
  50. * @return
  51. */
  52. public String executePost(String url,String contentType,String encoding,String param)
  53. {
  54. HttpPost httpPost = new HttpPost(url);
  55. try {
  56. httpPost.setConfig(requestConfig);
  57. this.initMethodParam(httpPost, contentType, encoding);
  58. if(param!=null)
  59. {
  60. httpPost.setEntity(new StringEntity(param, encoding));//设置请求体
  61. }
  62. return this.execute(httpPost,httpClient);
  63. }
  64. catch (Exception e)
  65. {
  66. throw new RuntimeException(e.getMessage(), e);
  67. }
  68. finally
  69. {
  70. httpPost.releaseConnection();
  71. }
  72. }
  73.  
  74. /**
  75. * 发送get请求
  76. * @param url 请求地址
  77. * @param contentType 请求类型
  78. * @param encoding 编码格式
  79. * @return
  80. */
  81. public String executeGet(String url,String contentType,String encoding){
  82. HttpGet httpGet = new HttpGet(url);
  83. try{
  84. httpGet.setConfig(requestConfig);
  85. this.initMethodParam(httpGet, contentType, encoding);
  86. return this.execute(httpGet,httpClient);
  87. }catch (Exception e){
  88. throw new RuntimeException(e.getMessage(),e);
  89. }finally{
  90. httpGet.releaseConnection();
  91. }
  92. }
  93. /**
  94. * 通用方法,用来发送post或get请求
  95. * @param method 请求类型
  96. * @param httpClient
  97. * @return
  98. * @throws RuntimeException
  99. * @throws IOException
  100. */
  101. private String execute(HttpUriRequest method,CloseableHttpClient httpClient) throws RuntimeException,IOException{
  102. CloseableHttpResponse response = null;
  103. try{
  104. response = httpClient.execute(method);
  105. HttpEntity entity = response.getEntity();
  106. return EntityUtils.toString(entity, method.getFirstHeader(HttpHeaders.CONTENT_ENCODING).getValue());
  107. }catch (Exception e){
  108. throw new RuntimeException(e.getMessage(), e);
  109. }finally{
  110. if(response != null){
  111. response.close();
  112. }
  113. }
  114. }
  115.  
  116. private void initMethodParam(HttpUriRequest method, String contentType, String encoding){
  117. if (contentType != null){
  118. method.setHeader(HttpHeaders.CONTENT_TYPE, contentType);
  119. }
  120. method.setHeader(HttpHeaders.CONTENT_ENCODING, encoding);
  121. method.setHeader(HttpHeaders.TIMEOUT, "60000");
  122. }
  123.  
  124. /**
  125. * 设置初始值
  126. */
  127. private void initRequestConfig() {
  128. requestConfig=RequestConfig.custom().setSocketTimeout(timeOut).setConnectTimeout(timeOut).build();
  129. }
  130.  
  131. /**
  132. * 获取主体类:
  133. * isHttps 区分https 和 https
  134. * @param isHttps
  135. * @return
  136. */
  137. private CloseableHttpClient getHttpClient(boolean isHttps) {
  138. CloseableHttpClient chc = null;
  139. try{
  140. if (isHttps){
  141. TrustManager[] trustManagers = new TrustManager[1];
  142. trustManagers[0] = new X509TrustManager(){
  143. public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException{}
  144. public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException{}
  145. public X509Certificate[] getAcceptedIssuers(){
  146. return null;
  147. }
  148. };
  149. SSLContext sslContext = SSLContext.getInstance("TLS");
  150. sslContext.init(new KeyManager[0], trustManagers, new SecureRandom());
  151. SSLContext.setDefault(sslContext);
  152. sslContext.init(null, trustManagers, null);
  153. SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  154. chc = HttpClients.custom().setSSLSocketFactory(sslsf).build();
  155. }else{
  156. chc=HttpClients.custom().build();
  157. }
  158. }catch (Exception e){
  159. throw new RuntimeException(e.getMessage(), e);
  160. }
  161. return chc;
  162. }
  163.  
  164. /**
  165. * 关闭链接
  166. */
  167. public void destroy(){
  168. System.out.println("方法被执行");
  169. try{
  170. httpClient.close();
  171. }catch (IOException e){
  172. throw new RuntimeException(e.getMessage(),e);
  173. }
  174. }
  175. }

服务端接口

  1. @RequestMapping(value="/txp/test.action",method= RequestMethod.POST)
  2. public void testHttpPost(HttpServletRequest request, HttpServletResponse response) throws Exception{
  3. //解析请求报文
  4. request.setCharacterEncoding("UTF-8"); //返回页面防止出现中文乱码
  5. BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));//post方式传递读取字符流
  6. String jsonStr = null;
  7. StringBuilder sb = new StringBuilder();
  8. try {
  9. while ((jsonStr = reader.readLine()) != null) {
  10. sb.append(jsonStr);
  11. }
  12. } catch (IOException e) {
  13. e.printStackTrace();
  14. }
  15. reader.close();// 关闭输入流
  16. System.out.println("请求报文:"+sb.toString());
  17. String result = "true";
  18. response.getWriter().print(result);
  19. }

测试方法

  1. @Test
  2. public void test(){
  3. //组装回调参数
  4. StringBuilder sb = new StringBuilder();
  5. sb.append("<?xml version=\"1.0\"?>");
  6. sb.append("<root>");
  7. sb.append("<param1>").append("hello word").append("</param1>");
  8. sb.append("<param2>").append("!").append("</param2>");
  9. sb.append("</root>");
  10.  
  11. //开始进行回调
  12. log.info("回调信息,{}",sb.toString());
  13. String responseBody = hd.executePost("http://localhost:7082/ecurrency-cardtransfer/txp/test.action", "text/xml", "GBK", sb.toString());
  14. System.out.println("返回信息:"+responseBody);
  15. }

HttpComponents 发送post get 请求的更多相关文章

  1. httpcomponents 发送get post请求

    引入的包为: <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --> <de ...

  2. HttpUtil工具类,发送Get/Post请求,支持Http和Https协议

    HttpUtil工具类,发送Get/Post请求,支持Http和Https协议 使用用Httpclient封装的HttpUtil工具类,发送Get/Post请求 1. maven引入httpclien ...

  3. 如果调用ASP.NET Web API不能发送PUT/DELETE请求怎么办?

    理想的RESTful Web API采用面向资源的架构,并使用请求的HTTP方法表示针对目标资源的操作类型.但是理想和现实是有距离的,虽然HTTP协议提供了一系列原生的HTTP方法,但是在具体的网络环 ...

  4. 调用webapi 错误:使用 HTTP 谓词 POST 向虚拟目录发送了一个请求,而默认文档是不支持 GET 或 HEAD 以外的 HTTP 谓词的静态文件。的解决方案

    第一次调用webapi出错如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http:// ...

  5. 从零开始学习Node.js例子七 发送HTTP客户端请求并显示响应结果

    wget.js:发送HTTP客户端请求并显示响应的各种结果 options对象描述了将要发出的请求.data事件在数据到达时被触发,error事件在发生错误时被触发.HTTP请求中的数据格式通过MIM ...

  6. 使用 HttpWebRequest 发送模拟 POST 请求

    使用HttpWebRequest发送模拟POST请求  网页中,如果form的method="POST",这时点击submit按钮可以给服务器发送了一个POST请求,如果metho ...

  7. IOS学习之路十八(通过 NSURLConnection 发送 HTTP 各种请求)

    你想通过 Http 协议向服务器发送一个 Get 的包装请求,并在这个请求中添加了一些请 求参数. 向远程服务器发送一个 GET 请求,然后解析返回的数据.通常一个 GET 请求是添加了 一些参数的, ...

  8. 发送POST测试请求的若干方法

    最近在工作中需要测试发送带Json格式body值的HTTP POST请求.起初,我在Linux环境下使用curl命令去发送请求,但是,在发送的过程中却遇到了一些问题,经过一段时间的摸索,发现了以下几种 ...

  9. Postman教程——发送第一个请求

    系列文章首发平台为果冻想个人博客.果冻想,是一个原创技术文章分享网站.在这里果冻会分享他的技术心得,技术得失,技术人生.我在果冻想等待你,也希望你能和我分享你的技术得与失,期待. 前言 过年在家,闲来 ...

随机推荐

  1. Oracle与Mysql区别简述

    在Mysql中,一个用户下可以创建多个库: 而在Oracle中,Oracle服务器是由两部分组成 数据库实例[理解为对象,看不见的] 数据库[理解为类,看得见的] 一个数据库实例可拥有多个用户,一个用 ...

  2. 监听器第一篇【基本概念、Servlet各个监听器】

    什么是监听器 监听器就是一个实现特定接口的普通java程序,这个程序专门用于监听另一个java对象的方法调用或属性改变,当被监听对象发生上述事件后,监听器某个方法将立即被执行. 为什么我们要使用监听器 ...

  3. session get和load方法对比

    get测试代码如下: public class Test { public static void main(String[] args) { // TODO Auto-generated metho ...

  4. Jmeter之性能测试基础

    1.概念:性能测试是通过自动化的测试工具模拟多种正常峰值及负载条件来对系统的各项性能指标进行测试.负载测试和压力测试都属于性能测试,两者可以结合进行.通过负载测试,确定在各种工作负载下系统的性能,目标 ...

  5. Linux配置SSH端口以及密钥登录

    改端口后重启: vim /etc/ssh/sshd_config systemctl restart sshd

  6. springboot+swagger2

    springboot+swagger2 小序 新公司的第二个项目,是一个配置管理终端机(比如:自动售卖机,银行取款机)的web项目,之前写过一个分模块的springboot框架,就在那个框架基础上进行 ...

  7. js中如何在一个函数里面执行另一个函数

    1.js中如何在函数a里面执行函数b function a(参数c){ b(); } function b(参数c){ } 方法2: <script type="text/javasc ...

  8. AFN默认请求和响应的处理

       1.默认的响应的解析      1.1 AFN默认不支持接受text/html数据类型,只需要增加即可     manager.responseSerializer.acceptableCont ...

  9. ThinkPHP中:用户登录权限验证类

    使用CommonAction.class.php公共类,统一判断用户是否登录 <?php //后台登录页 Class CommonAction extends Action{ //后台登录页面 ...

  10. 一个基于Asp.net MVC的博客类网站开源了!

    背景说明: 大学时毕业设计作品,一直闲置在硬盘了,倒想着不如开源出来,也许会对一些人有帮助呢,而且个人觉得这个网站做得还是不错了,毕竟是花了不少心思,希望对你有所帮助. github地址:https: ...