1.场景描述

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

2.HttpComponents项目的介绍

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

3.maven依赖 

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.1</version>
</dependency>

4.代码编写

工具类

import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; /**
* apache httpclient 工具类
* 支持对 http https 接口调用
* <P>
* 1.GET 请求
* 2.POST 请求
* </P>
*/
public class HttpDelegate {
private int timeOut = 10000;//指定超时时间
private CloseableHttpClient httpClient;
private RequestConfig requestConfig;//设置请求参数 /**
* 对象被创建时执行
*/
public HttpDelegate(Boolean isHttps){
httpClient = this.getHttpClient(isHttps);
this.initRequestConfig();//初始化请求配置
} /**
* 发送post请求
* @param url 请求地址
* @param contentType 请求类型
* @param encoding 编码格式
* @param param 请求参数
* @return
*/
public String executePost(String url,String contentType,String encoding,String param)
{
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setConfig(requestConfig);
this.initMethodParam(httpPost, contentType, encoding);
if(param!=null)
{
httpPost.setEntity(new StringEntity(param, encoding));//设置请求体
}
return this.execute(httpPost,httpClient);
}
catch (Exception e)
{
throw new RuntimeException(e.getMessage(), e);
}
finally
{
httpPost.releaseConnection();
}
} /**
* 发送get请求
* @param url 请求地址
* @param contentType 请求类型
* @param encoding 编码格式
* @return
*/
public String executeGet(String url,String contentType,String encoding){
HttpGet httpGet = new HttpGet(url);
try{
httpGet.setConfig(requestConfig);
this.initMethodParam(httpGet, contentType, encoding);
return this.execute(httpGet,httpClient);
}catch (Exception e){
throw new RuntimeException(e.getMessage(),e);
}finally{
httpGet.releaseConnection();
}
}
/**
* 通用方法,用来发送post或get请求
* @param method 请求类型
* @param httpClient
* @return
* @throws RuntimeException
* @throws IOException
*/
private String execute(HttpUriRequest method,CloseableHttpClient httpClient) throws RuntimeException,IOException{
CloseableHttpResponse response = null;
try{
response = httpClient.execute(method);
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity, method.getFirstHeader(HttpHeaders.CONTENT_ENCODING).getValue());
}catch (Exception e){
throw new RuntimeException(e.getMessage(), e);
}finally{
if(response != null){
response.close();
}
}
} private void initMethodParam(HttpUriRequest method, String contentType, String encoding){
if (contentType != null){
method.setHeader(HttpHeaders.CONTENT_TYPE, contentType);
}
method.setHeader(HttpHeaders.CONTENT_ENCODING, encoding);
method.setHeader(HttpHeaders.TIMEOUT, "60000");
} /**
* 设置初始值
*/
private void initRequestConfig() {
requestConfig=RequestConfig.custom().setSocketTimeout(timeOut).setConnectTimeout(timeOut).build();
} /**
* 获取主体类:
* isHttps 区分https 和 https
* @param isHttps
* @return
*/
private CloseableHttpClient getHttpClient(boolean isHttps) {
CloseableHttpClient chc = null;
try{
if (isHttps){
TrustManager[] trustManagers = new TrustManager[1];
trustManagers[0] = new X509TrustManager(){
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException{}
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException{}
public X509Certificate[] getAcceptedIssuers(){
return null;
}
};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(new KeyManager[0], trustManagers, new SecureRandom());
SSLContext.setDefault(sslContext);
sslContext.init(null, trustManagers, null);
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
chc = HttpClients.custom().setSSLSocketFactory(sslsf).build();
}else{
chc=HttpClients.custom().build();
}
}catch (Exception e){
throw new RuntimeException(e.getMessage(), e);
}
return chc;
} /**
* 关闭链接
*/
public void destroy(){
System.out.println("方法被执行");
try{
httpClient.close();
}catch (IOException e){
throw new RuntimeException(e.getMessage(),e);
}
}
}

服务端接口

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

测试方法

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

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. 201521123028 《Java程序设计》 第9周学习总结

    1. 本周学习总结 2. 书面作业 Q1.常用异常 题目5-1 1.1 截图你的提交结果(出现学号) 1.2 自己以前编写的代码中经常出现什么异常.需要捕获吗(为什么)?应如何避免? Ans: 在JA ...

  2. Hyperledger Fabric 1.0 从零开始(五)——运行测试e2e

    3:运行测试e2e 3.1.运行fabric-samples的问题说明 该问题说明能够解决6.1.平台特定使用的二进制文件配置第一步的问题.可以选择继续阅读该说明,或者等参考到6.1小节时再反向阅读本 ...

  3. 生成/etc/shadow文件中的密码

    shadow文件的格式就不说了.就说说它的第二列--密码列. 通常,passwd直接为用户指定密码就ok了.但在某些情况下,要为待创建的用户事先指定密码,还要求是加密后的密码,例如kickstart文 ...

  4. 如何在mybatis 中使用In操作

    如何在mybatis 中使用In操作 假如我们想使用这样一个sql 语句,但是这样的sql语句有IN这样的操作.在我们的mybatis中有相对应的操作 SELECT * FROM product_db ...

  5. Git的使用详解

    起步 关于版本控制 Git 简史 Git 基础 安装 Git 初次运行 Git 前的配置 获取帮助 小结 Git 基础 取得项目的 Git 仓库 记录每次更新到仓库 查看提交历史 撤消操作 远程仓库的 ...

  6. thinkphp5.0无限极分类及格式化输出

    首先我们来看数据表 从上图中可以发现,中国下有贵州,北京两个子节点,而北京有天安门一个子节点,纽约的子节点是"纽约的子类". 从pid为0看出,中国和纽约是顶级节点. 因为贵州的p ...

  7. javaWeb正则表达式

    对于web来说,字符串的处理特别重要,而正则表达式是对字符串处理的利器,在字符过滤,验证方面都能看到她的身影. 今天需要处理一段json字符串,在用String.replaceAll的过程中,遇到了正 ...

  8. 在JavaScript中使用json.js:Ajax项目之GET请求(同步)

    1.用php编写一个提供数据的响应程序(phpdata.php) <?php $arr=array(1,2,3,4); //将数组编码为JSON格式的数据 $jsonarr=json_encod ...

  9. Spark官方2 ---------Spark 编程指南(1.5.0)

    概述 在高层次上,每个Spark应用程序都由一个运行用户main方法的driver program组成,并在集群上执行各种 parallel operations.Spark提供的主要抽象是resil ...

  10. Android Studio安装应用时报错 installation failed with message Failed to finalize session......

    解决方法: 在AndroidManifest.xml中的provider中的authorities后加几个数字即可. 2017.09.01: 我发现有的项目AndroidManifest.xml中没有 ...