一、使用方法

使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。

1. 创建HttpClient对象。

2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。

3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。

4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。

5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。

6. 释放连接。无论执行方法是否成功,都必须释放连接

二、实例

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; 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.utils.URIBuilder;
import org.apache.http.entity.ContentType;
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 static String doGet(String url, Map<String, String> param) { // 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault(); String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build(); // 创建http GET请求
HttpGet httpGet = new HttpGet(uri); // 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
} public static String doGet(String url) {
return doGet(url, null);
} public static String doPost(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} return resultString;
} public static String doPost(String url) {
return doPost(url, null);
} public static String doPostJson(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} return resultString;
}

使用HttpClient发送请求的一般步骤
(1) 创建HttpClient对象。
(2)创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
(3) 如果需要发送请求参数,可调用HttpGet同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,可调用setEntity(HttpEntity entity)方法来设置请求参数。
(4) 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
(5) 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
(6) 释放连接。无论执行方法是否成功,都必须释放连接

代码如下:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
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;
import org.apache.log4j.Logger;

public class HttpTest {

protected static Logger logger = Logger.getLogger(HttpTest.class);
//请求超时时间,这个时间定义了socket读数据的超时时间,也就是连接到服务器之后到从服务器获取响应数据需要等待的时间,发生超时,会抛出SocketTimeoutException异常。
private static final int SOCKET_TIME_OUT = 60000;
//连接超时时间,这个时间定义了通过网络与服务器建立连接的超时时间,也就是取得了连接池中的某个连接之后到接通目标url的连接等待时间。发生超时,会抛出ConnectionTimeoutException异常
private static final int CONNECT_TIME_OUT = 60000; private static List<NameValuePair> createParam(Map<String, Object> param) {
//建立一个NameValuePair数组,用于存储欲传送的参数
List<NameValuePair> nvps = new ArrayList <NameValuePair>();
if(param != null) {
for(String k : param.keySet()) {
nvps.add(new BasicNameValuePair(k, param.get(k).toString()));
}
}
return nvps;
} /**
* 发送 post 请求
* @param url 请求地址,如 http://www.baidu.com
* @param param相关参数, 模拟form 提交
* @return
* @throws Exception
*/
public static String postForAPP(String url, String sMethod, Map<String, Object> param, Map<String, Object> headers) throws Exception {
//目前HttpClient最新版的实现类为CloseableHttpClient
CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = null;
HttpEntity entity=null;
try {
if(param != null) {
//建立Request的对象,一般用目标url来构造,Request一般配置addHeader、setEntity、setConfig
HttpPost req = new HttpPost(url);
entity=new UrlEncodedFormEntity(createParam(param), Consts.UTF_8);
//setHeader,添加头文件
Set<String> keys = headers.keySet();
for (String key : keys) {
req.setHeader(key, headers.get(key).toString());
}
//setConfig,添加配置,如设置请求超时时间,连接超时时间
RequestConfig reqConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIME_OUT).setConnectTimeout(CONNECT_TIME_OUT).build();
req.setConfig(reqConfig);
//setEntity,添加内容
req.setEntity(entity);
//执行Request请求,CloseableHttpClient的execute方法返回的response都是CloseableHttpResponse类型
//其常用方法有getFirstHeader(String)、getLastHeader(String)、headerIterator(String)取得某个Header name对应的迭代器、getAllHeaders()、getEntity、getStatus等
response = client.execute(req);
entity = response.getEntity();
//用EntityUtils.toString()这个静态方法将HttpEntity转换成字符串,防止服务器返回的数据带有中文,所以在转换的时候将字符集指定成utf-8就可以了
String result= EntityUtils.toString(entity, "UTF-8");
logger.error("-------------------------"+result+"-------------");
if(response.getStatusLine().getStatusCode()==200){
logger.error(result+"-----------success------------------");
return result;
}else{
logger.error(response.getStatusLine().getStatusCode()+"------------------fail-----------");
return null;
}
}
return null;
} catch(Exception e) {
logger.error("--------------------------post error: ", e);
throw new Exception();
}finally{
//一定要记得把entity fully consume掉,否则连接池中的connection就会一直处于占用状态
EntityUtils.consume(entity);
logger.error("---------------------------finally-------------");
System.out.println("---------------------------------------------------");
}
} public static void main(String[] args) throws Exception {
Map<String, Object> param=new HashMap<String, Object>();
param.put("pdata", "mm");
Map<String, Object> headers=new HashMap<String, Object>();
headers.put("appid", "mm");
postForAPP("http://localhost:8080/SpringMVC-httpclient/greeting", "aa", param, headers);
}

最新文章

  1. iOS导航栏的正确隐藏方式【转】
  2. asp.net与Matlab类型转换(待补全)
  3. Dijkstra(歪果仁的名字真是长。。。)
  4. JVM-类文件结构
  5. 【BZOJ】【1004】【HNOI2008】Cards
  6. ubuntu ip
  7. 【搜索】BZOJ 3990: 【Sdoi 2015】排序
  8. 【Oracle连接字符串】【Oracle Net Manager 服务命名配置】【PL/SQL 登陆数据库】
  9. Ubuntu 16.04 - 64bit 访问Windows磁盘报错 he NTFS partition is in an unsafe state. Please resume and shutdown Windows fully (no hibernation ...
  10. sql2005中如何启用SA账号
  11. (转)直接保存对象的数据库——db4o
  12. BZOJ 3211 花神游历各国 (树状数组+并查集)
  13. BCDBOOT命令参数介绍
  14. Elasticsearch 默认配置 IK 及 Java AnalyzeRequestBuilder 使用
  15. MySQL注释中的sql也可能执行
  16. ROS机器人程序设计(原书第2版)补充资料 (贰) 第二章 ROS系统架构及概念
  17. python_类与对象学习笔记
  18. java JDBC (一)
  19. LOJ 10138 -「一本通 4.5 例 1」树的统计
  20. 【Windows】DOS的常用命令

热门文章

  1. SaltStack自动化软件简介及安装
  2. C语言数据结构——第二章 线性表
  3. Mysql SQL CAST()函数
  4. Linux05——用户操作
  5. 如何在windows和linux搭建django环境
  6. winform中的DataGridView的列宽设置
  7. Multisim 之逻辑转换仪
  8. 排序算法之归并排序的python实现
  9. 安卓基础(AndroidViewModel)
  10. Solr 8.2.0最新RCE漏洞复现