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

    201521123045 <Java程序设计>第9周学习总结 1. 本章学习总结 2. 书面作业 本次PTA作业题集异常 1.常用异常题目5-11.1 截图你的提交结果(出现学号) 1.2 ...

  2. MUI如何调取相册的方法

    第一种是HTML方法 <label> <input style="opacity: 0;" type="file" accept=" ...

  3. Java-大集合拆分为指定大小的小集合

    因为Oracle数据的in 最大允许1000 ,超过就会报错, 所以需要将集合拆分为多个集合进行处理. /** * 拆分集合 * @param <T> * @param resList 要 ...

  4. json-java处理-jackson

    使用jackson处理json数据 maven中的配置,这里没有写版本信息 <dependency> <groupId>org.codehaus.jackson</gro ...

  5. Python初识2

    27.Python中没有{}括起来的代码块,使用pass来代替c语言中的{(无内容)}: 28.使用__name__来指示模块是如何加载的,如果是被导入的,那么__name__就是该模块的名字,如果是 ...

  6. EF 6.0

    最近又开始研究EF框架了 哎 搞的东西太杂了 网上的参考了一篇博客 但是他是基于EF 4.0之前做的 所以自己基于他的博客来构造EF 6.0的使用基础 命名空间不同: 旧版本:using System ...

  7. 代理模式与java中的动态代理

    前言    代理模式又分为静态代理与动态代理,其中动态代理是Java各大框架中运用的最为广泛的一种模式之一,下面就用简单的例子来说明静态代理与动态代理. 场景    李雷是一个唱片公司的大老板,很忙, ...

  8. 大牛教你用3行HTML代码卡死一台机器

    前言 学习web渗透测试等安全工作的朋友们,想必大部分接触的最早的就是HTML了. 其实学过html的朋友们都知道,html中可以插入JavaScript代码,而对于JavaScript代码,这里就不 ...

  9. Excel更改单元格格式后无效

    问题描述: 比如修改了数据的自定义显示格式(日期显示 yyyy"年"m"月",手机号分段000-0000-0000),应用后发现只有部分生效,或者都不生效,再检 ...

  10. Docker入门之六端口映射与容器互联

    一.端口映射 在之前的博客搭建私有仓库时用到这样一句:docker run -d -p 5000:5000 -v /opt/data/registry:/tmp/registry registry来r ...