一,介绍

创建一个HttpRequest类,该类负责向服务器发起HTTP GET, POST请求。该类的对象使用单例模式来创建,因为对于多个客户端而言,需要发送大量的HTTP请求,而每一个请求都需要调用HttpRequest类的方法向服务器建立连接,因此每一个请求都创建一个HttpRequest对象的话,对资源消耗很大。

二,发送请求

1,无参数的GET请求

 public String doGet(String uri){HttpGet httpGet = new HttpGet(uri);return sendHttpGet(httpGet);}

2,带多个参数的GET请求

public String doGet(String uri, List<NameValuePair> parameters){HttpGet httpGet = new HttpGet(uri);String param = null;try{param = EntityUtils.toString(new UrlEncodedFormEntity(parameters));//build get uri with paramshttpGet.setURI(new URIBuilder(httpGet.getURI().toString() + "?" + param).build());}catch(Exception e){e.printStackTrace();}return sendHttpGet(httpGet);}

GET请求的多个参数以NameValuePair类型存储在List列表中。通过EntityUtils类将NameValuePair解析成String变量param,然后再使用URIBuilder类重新构造一个带参数的HTTP GET 请求。

三,发送POST请求

1,无参数的POST请求

public String doPost(String uri){HttpPost httpPost = new HttpPost(uri);return sendHttpPost(httpPost);}

2,带一个参数的POST请求

 public String doGet(String uri, String paramName, String paramValue){HttpGet httpGet = new HttpGet(uri);//build get uri with paramsURIBuilder uriBuilder = new URIBuilder(httpGet.getURI()).setParameter(paramName, paramValue);try{httpGet.setURI(uriBuilder.build());}catch(URISyntaxException e){e.printStackTrace();}return sendHttpGet(httpGet);}

使用URIBuilder的 setParameter方法为POST URI添加请求参数。当需要带多个参数的POST请求时,可借助Lists<NameValuePair>,参考上面“带多个参数的GET请求”的实现方式。

3,使用POST请求发送XML内容实体。

public String doPost(String uri, String reqXml){HttpPost httpPost = new HttpPost(uri);httpPost.addHeader("Content-Type", "application/xml");StringEntity entity = null;try{entity = new StringEntity(reqXml, "UTF-8");}catch(Exception e){e.printStackTrace();}httpPost.setEntity(entity);//http post with xml datareturn sendHttpPost(httpPost);}

XML内容实体以 String reqXml参数表示。首先为请求添加Header表示内容实体的类型-"application/xml",然后使用StringEntity类包装内容实体。最后调用HttpPost的setEntity()封装内容实体,并发送。

三,与服务器建立HTTP连接

1,建立GET连接

private String sendHttpGet(HttpGet httpGet){CloseableHttpClient httpClient = null;CloseableHttpResponse response = null;HttpEntity entity = null;String responseContent = null;try{httpClient = HttpClients.createDefault();
//          httpGet.setConfig(config);response = httpClient.execute(httpGet);entity = response.getEntity();responseContent = EntityUtils.toString(entity, "UTF-8");}catch(Exception e){e.printStackTrace();}finally{try{if(response != null)response.close();if(httpClient != null)httpClient.close();}catch(IOException e){e.printStackTrace();}}return responseContent;}

HttpEntity entity 是服务器发回的响应实体,由EntityUtils类的toString()方法 转换字符串后,返回给调用者。

建立POST连接和PUT连接,参考整个完整代码:

package http;import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;public class HttpRequest {private static HttpRequest httpRequest = null;private HttpRequest(){}public static HttpRequest getInstance(){if(httpRequest == null){synchronized (HttpRequest.class) {if(httpRequest == null)httpRequest = new HttpRequest();}}return httpRequest;}public String doGet(String uri){HttpGet httpGet = new HttpGet(uri);return sendHttpGet(httpGet);}/** only one paramter's http get request*/public String doGet(String uri, String paramName, String paramValue){HttpGet httpGet = new HttpGet(uri);//build get uri with paramsURIBuilder uriBuilder = new URIBuilder(httpGet.getURI()).setParameter(paramName, paramValue);try{httpGet.setURI(uriBuilder.build());}catch(URISyntaxException e){e.printStackTrace();}return sendHttpGet(httpGet);}/** mulitple paramters of http get request*/public String doGet(String uri, List<NameValuePair> parameters){HttpGet httpGet = new HttpGet(uri);String param = null;try{param = EntityUtils.toString(new UrlEncodedFormEntity(parameters));//build get uri with paramshttpGet.setURI(new URIBuilder(httpGet.getURI().toString() + "?" + param).build());}catch(Exception e){e.printStackTrace();}return sendHttpGet(httpGet);}public String doPost(String uri){HttpPost httpPost = new HttpPost(uri);return sendHttpPost(httpPost);}public String doPost(String uri, String reqXml){HttpPost httpPost = new HttpPost(uri);httpPost.addHeader("Content-Type", "application/xml");StringEntity entity = null;try{entity = new StringEntity(reqXml, "UTF-8");}catch(Exception e){e.printStackTrace();}httpPost.setEntity(entity);//http post with xml datareturn sendHttpPost(httpPost);}/** multiple http put params*/public String doPut(String uri, List<NameValuePair> parameters){HttpPut httpPut = new HttpPut(uri);String param = null;try{param = EntityUtils.toString(new UrlEncodedFormEntity(parameters));httpPut.setURI(new URIBuilder(httpPut.getURI().toString() + "?" + param).build());}catch(Exception e){e.printStackTrace();}return sendHttpPut(httpPut);}public String doPut(String uri, List<NameValuePair> parameters, String reqXml){HttpPut httpPut = new HttpPut(uri);String param = null;try{param = EntityUtils.toString(new UrlEncodedFormEntity(parameters));httpPut.setURI(new URIBuilder(httpPut.getURI().toString() + "?" + param).build());}catch(Exception e){e.printStackTrace();}StringEntity entity = null;try{entity = new StringEntity(reqXml, "UTF-8");}catch(Exception e){e.printStackTrace();}httpPut.setEntity(entity);return sendHttpPut(httpPut);}private String sendHttpPost(HttpPost httpPost){CloseableHttpClient httpClient = null;CloseableHttpResponse response = null;HttpEntity entity = null;String responseContent = null;try{httpClient = HttpClients.createDefault();
//          httpPost.setConfig(config);response = httpClient.execute(httpPost);entity = response.getEntity();responseContent = EntityUtils.toString(entity, "UTF-8");}catch (Exception e) {e.printStackTrace();}finally{try{if(response != null)response.close();if(httpClient !=null)httpClient.close();}catch(IOException e){e.printStackTrace();}}return responseContent;}private String sendHttpGet(HttpGet httpGet){CloseableHttpClient httpClient = null;CloseableHttpResponse response = null;HttpEntity entity = null;String responseContent = null;try{httpClient = HttpClients.createDefault();
//          httpGet.setConfig(config);response = httpClient.execute(httpGet);entity = response.getEntity();responseContent = EntityUtils.toString(entity, "UTF-8");}catch(Exception e){e.printStackTrace();}finally{try{if(response != null)response.close();if(httpClient != null)httpClient.close();}catch(IOException e){e.printStackTrace();}}return responseContent;}private String sendHttpPut(HttpPut httpPut){CloseableHttpClient httpClient = null;CloseableHttpResponse response = null;HttpEntity entity = null;String responseContent = null;try{httpClient = HttpClients.createDefault();
//          httpPut.setConfig(config);response = httpClient.execute(httpPut);entity = response.getEntity();responseContent = EntityUtils.toString(entity, "UTF-8");}catch(Exception e){e.printStackTrace();}return responseContent;}
}

参考:http://tzz6.iteye.com/blog/2224757

http://blog.csdn.net/sunny243788557/article/details/8106265

使用Apache HttpClient4.x 发送 GET POST 请求相关推荐

  1. 如何设置Fiddler来拦截Java代码发送的HTTP请求,进行各种问题排查

    我们使用Java的RestTemplate或者Apache的HTTPClient编程的时候,经常遇到需要跟踪Java 代码发送的HTTP请求明细的情况.和javascript代码在浏览器里发送请求可以 ...

  2. 服务器响应options,HTTP发送对OPTIONS请求的响应[C]

    在接收HTTP响应时出现Response is null错误. 我正在开发一个使用行套接字的示例小型HTTP服务器C.HTTP发送对OPTIONS请求的响应[C] 我的应用程序中实际上有2个服务器,一 ...

  3. JAVA解决OPTIONS请求问题:跨域时ajax发送两次请求,其中options预请求参数为null及其解决方案

    转载请注明出处 原文链接:https://blog.csdn.net/qq_39309348/article/details/103267908 在正式跨域的请求前,浏览器会根据需要,发起一个&quo ...

  4. postman无法获得响应_【原创翻译】POSTMAN从入门到精通系列(二):发送第一个请求...

    通过API请求,您可以与具有要访问的API端点的服务器联系,并执行某些操作.这些操作是HTTP方法. 最常用的方法是GET,POST,PUT和DELETE.方法的名称是不言自明的.例如,GET使您可以 ...

  5. ajax 跨域请求,每次会发送两个请求?

    2019独角兽企业重金招聘Python工程师标准>>> 跨域已经是个老话题了,但是最近搞百度的语音接口的时候,在服务端配置了 CORS ,跨域倒是没问题,但是每次都会发送两个请求: ...

  6. python同时同步发送多个请求_python如何实现“发送一个请求,等待多个响应”的同步?...

    我正在写一些代码通过串行口与单片机通信. MCU端基本上是一个请求/响应服务器. 一个或多个MCU发送我的请求. 然而,响应可以异步到达并且具有随机延迟,但是响应的顺序将保持不变. 另外,我的应用程序 ...

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

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

  8. 解决python发送multipart/form-data请求上传文件的问题

    解决python发送multipart/form-data请求上传文件的问题 参考文章: (1)解决python发送multipart/form-data请求上传文件的问题 (2)https://ww ...

  9. apache httpclient4 设置超时时间

    2019独角兽企业重金招聘Python工程师标准>>> apache httpclient4 设置超时时间 旧的方法(已被禁用) CloseableHttpClient httpcl ...

最新文章

  1. 详解谷歌最强NLP模型BERT(理论+实战)
  2. HP-UX B.11.31从安装到VG配置
  3. QT自定义图表上不同元素的外观
  4. python对象_查找Python对象具有的方法
  5. java 过滤xss脚本_Java Web应用程序的反跨站点脚本(XSS)过滤器
  6. SQLAlchemy Mapping Class Inheritance Hierarchies
  7. 笔记-配置博客园客户端代码高亮(2016.08.20)
  8. python登录网页版易信_易信网页版下载|易信网页版登陆客户端官方最新版 2.1.1103.0 - 系统天堂...
  9. UIAutomator2.0初始
  10. Microsoft .NET Framework 3.5 SP1 简体中文精简版+.net
  11. excel文件损坏修复绝招_电脑常识:电脑提示dll文件丢失/损坏,该怎么修复?...
  12. 小美赛:模拟机舱病毒传播
  13. 如何用CSS3画出一个立体魔方?
  14. 我学炒外汇 第十三篇影响瑞士法郎的因素
  15. caffe 报错 Aborted(core dumped
  16. ppt 计算机图标不见了,我PPT的图标变成这样了,为什么
  17. Sharding-JDBC(二)- Sharding-JDBC介绍
  18. RNA-seq与miRNA-seq联合分析
  19. PIC16F630使用PICkit程序下载使用方法
  20. Flutter现支持Web和桌面,一跃成为前沿大一统框架,【面试必备】

热门文章

  1. Silverlight游戏研发手记:(五)SLG动感增效之《幻影粒子》
  2. 魅蓝note3联通卡显示无服务器,竟然有这么多bug?面对魅蓝note3犹豫了
  3. django 第一个web页面
  4. 计算机没有autoCAD_计算机辅助设计3D软件大全autocad2010 2014 2018
  5. 介绍Python/Django的在线好书推荐
  6. 89c51c语言程序,89C51单片机计算器C语言程序.doc
  7. EDMA SEED 例程
  8. 使用hinfric和hinflmi函数设计H∞输出反馈控制器(含实现程序)
  9. 因果推断(五)——反事实,后悔药?
  10. IRIS Docker的安装