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教程——发送第一个请求
系列文章首发平台为果冻想个人博客.果冻想,是一个原创技术文章分享网站.在这里果冻会分享他的技术心得,技术得失,技术人生.我在果冻想等待你,也希望你能和我分享你的技术得与失,期待. 前言 过年在家,闲来 ...
随机推荐
- Oracle与Mysql区别简述
在Mysql中,一个用户下可以创建多个库: 而在Oracle中,Oracle服务器是由两部分组成 数据库实例[理解为对象,看不见的] 数据库[理解为类,看得见的] 一个数据库实例可拥有多个用户,一个用 ...
- 监听器第一篇【基本概念、Servlet各个监听器】
什么是监听器 监听器就是一个实现特定接口的普通java程序,这个程序专门用于监听另一个java对象的方法调用或属性改变,当被监听对象发生上述事件后,监听器某个方法将立即被执行. 为什么我们要使用监听器 ...
- session get和load方法对比
get测试代码如下: public class Test { public static void main(String[] args) { // TODO Auto-generated metho ...
- Jmeter之性能测试基础
1.概念:性能测试是通过自动化的测试工具模拟多种正常峰值及负载条件来对系统的各项性能指标进行测试.负载测试和压力测试都属于性能测试,两者可以结合进行.通过负载测试,确定在各种工作负载下系统的性能,目标 ...
- Linux配置SSH端口以及密钥登录
改端口后重启: vim /etc/ssh/sshd_config systemctl restart sshd
- springboot+swagger2
springboot+swagger2 小序 新公司的第二个项目,是一个配置管理终端机(比如:自动售卖机,银行取款机)的web项目,之前写过一个分模块的springboot框架,就在那个框架基础上进行 ...
- js中如何在一个函数里面执行另一个函数
1.js中如何在函数a里面执行函数b function a(参数c){ b(); } function b(参数c){ } 方法2: <script type="text/javasc ...
- AFN默认请求和响应的处理
1.默认的响应的解析 1.1 AFN默认不支持接受text/html数据类型,只需要增加即可 manager.responseSerializer.acceptableCont ...
- ThinkPHP中:用户登录权限验证类
使用CommonAction.class.php公共类,统一判断用户是否登录 <?php //后台登录页 Class CommonAction extends Action{ //后台登录页面 ...
- 一个基于Asp.net MVC的博客类网站开源了!
背景说明: 大学时毕业设计作品,一直闲置在硬盘了,倒想着不如开源出来,也许会对一些人有帮助呢,而且个人觉得这个网站做得还是不错了,毕竟是花了不少心思,希望对你有所帮助. github地址:https: ...