HttpComponents 发送post get 请求
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 请求的更多相关文章
- httpcomponents 发送get post请求
引入的包为: <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --> <de ...
- HttpUtil工具类,发送Get/Post请求,支持Http和Https协议
HttpUtil工具类,发送Get/Post请求,支持Http和Https协议 使用用Httpclient封装的HttpUtil工具类,发送Get/Post请求 1. maven引入httpclien ...
- 如果调用ASP.NET Web API不能发送PUT/DELETE请求怎么办?
理想的RESTful Web API采用面向资源的架构,并使用请求的HTTP方法表示针对目标资源的操作类型.但是理想和现实是有距离的,虽然HTTP协议提供了一系列原生的HTTP方法,但是在具体的网络环 ...
- 调用webapi 错误:使用 HTTP 谓词 POST 向虚拟目录发送了一个请求,而默认文档是不支持 GET 或 HEAD 以外的 HTTP 谓词的静态文件。的解决方案
第一次调用webapi出错如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http:// ...
- 从零开始学习Node.js例子七 发送HTTP客户端请求并显示响应结果
wget.js:发送HTTP客户端请求并显示响应的各种结果 options对象描述了将要发出的请求.data事件在数据到达时被触发,error事件在发生错误时被触发.HTTP请求中的数据格式通过MIM ...
- 使用 HttpWebRequest 发送模拟 POST 请求
使用HttpWebRequest发送模拟POST请求 网页中,如果form的method="POST",这时点击submit按钮可以给服务器发送了一个POST请求,如果metho ...
- IOS学习之路十八(通过 NSURLConnection 发送 HTTP 各种请求)
你想通过 Http 协议向服务器发送一个 Get 的包装请求,并在这个请求中添加了一些请 求参数. 向远程服务器发送一个 GET 请求,然后解析返回的数据.通常一个 GET 请求是添加了 一些参数的, ...
- 发送POST测试请求的若干方法
最近在工作中需要测试发送带Json格式body值的HTTP POST请求.起初,我在Linux环境下使用curl命令去发送请求,但是,在发送的过程中却遇到了一些问题,经过一段时间的摸索,发现了以下几种 ...
- Postman教程——发送第一个请求
系列文章首发平台为果冻想个人博客.果冻想,是一个原创技术文章分享网站.在这里果冻会分享他的技术心得,技术得失,技术人生.我在果冻想等待你,也希望你能和我分享你的技术得与失,期待. 前言 过年在家,闲来 ...
随机推荐
- 201521123011《Java程序设计》第10周学习总结
1. 本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结异常与多线程相关内容. 2. 书面作业 本次PTA作业题集异常.多线程 1.finally 题目4-2 1.1 截图你的提交结果(出 ...
- Maven常见错误以及解决方案【转载】
常见的Maven错误 当遇到401错误的时候,看看自己当前使用的Maven是集成的还是自己下载的,然后去配置setting.xml文件
- Apache2.4 + Tomcat7 负载均衡配置
一.配置tomcat 多启动 1.下载免安装版 tomcat7 http://mirror.bit.edu.cn/apache/tomcat/tomcat-7/v7.0.81/bin/apache-t ...
- Struts2基于XML配置方式实现对Action方法进行校验
JavaWeb框架(2) 使用XML对Action方法进行校验方式有两种,一种是对Action的所有方法进行校验,另一种是对Action指定方法进行校验. 对Action的所有方法进行校验: 步骤: ...
- MongoDB的备份和部署 高级功能索引,聚合复制,分片
创建备份 MongoDB 数据转储 为了在 MongoDB 中创建数据库备份,需要使用 mongodump 命令.该命令会将服务器上的所有数据都转储到 dump 目录中.你可以使用很多选项来限制转储的 ...
- SQL映射文件实现多种方式查询
1.单条件查询在test中代码如下 2.多条件查询时需要把查询条件编辑为对象或者是集合传入,例如 通过对象进行查询 或者是通过集合进行查询列如Map集合 还有就是通过@Param注解实现多参数的入参, ...
- InnoDB Undo Log
简介 Undo Log包含了一系列在一个单独的事务中会产生的所有Undo Log记录.每一个Undo Log记录包含了如何undo事务对某一行修改的必要信息.InnoDB使用Undo Log来进行事务 ...
- 【重点突破】——Cookie的使用
cookie:小甜饼 cookie:保存客户端浏览器中一个纯文本文件 版本高的浏览器可查看 F12->Resource 左下方cookie 查看 cookie作用: 保存:[安全性要 ...
- Operating system hdu 2835 OPT
Operating system Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) ...
- 跨平台移动端APP开发---简单高效的MUI框架
MUI是dcloud(数字天堂)公司旗下的一款跨平台开发移动APP的框架产品,在学习MUI框架之前,最先接触了Hbuilder代码编辑器,它带给我的第一感觉是快,这是HBuilder的最大优势,通过完 ...