使用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) 释放连接。无论执行方法是否成功,都必须释放连接
HTTP的三种超时说明
1.connectionRequestTimout
指从连接池获取连接的timeout
2.connetionTimeout
指客户端和服务器建立连接的timeout,
就是http请求的三个阶段,一:建立连接;二:数据传送;三,断开连接。超时后会ConnectionTimeOutException
3.socketTimeout
指客户端和服务器建立连接后,客户端从服务器读取数据的timeout,超出后会抛出SocketTimeOutException
Get请求和Post请求其实只是HttpGet和HttpPost的区别Get的参数是跟在路径后面的而post的请求是需要
Post请求
String url = "请求路径如:http://www.baidu.com";
HttpClient httpClient = null;
HttpPost postMethod = null;
HttpResponse response = null;
RebackTokenEntity rebackTokenEntity = null;
/*设置连接超时时间*/
RequestConfig requestConfig = RequestConfig.custom().
setConnectionRequestTimeout(10000).
setConnectTimeout(10000).
setSocketTimeout(10000).
build();
postMethod.setConfig(requestConfig);
try {
httpClient = HttpClients.createDefault();
postMethod = new HttpPost(url);//传入URL地址
//设置请求头 指定为json
postMethod.addHeader("Content-type", "application/json;charset=UTF-8");
//传入请求参数 Class为我传入的对象参数
postMethod.setEntity(new StringEntity(Class.toString(), Charset.forName("UTF-8")));
response = httpClient.execute(postMethod);//获取响应
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
System.out.println("HTTP请求未成功!HTTP Status Code:" + response.getStatusLine());
}
HttpEntity httpEntity = response.getEntity();
String reponseContent = EntityUtils.toString(httpEntity,"UTF-8");
EntityUtils.consume(httpEntity);//释放资源
//用Gson将对象转化为实体类
Gson gson = new Gson();
Class= gson.fromJson(reponseContent, Class.class);
System.out.println("响应内容:" + reponseContent);
} catch (Exception e) {
e.printStackTrace();
}finally {
/*关闭连接资源*/
try {
if (response == null){
response.getEntity().getContent().close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Post请求Map传参
private static String doPost(String url, Map<String, Object> paramMap) {
String res = null;
HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod(url);
postMethod.getParams().setContentCharset("UTF-8");
Iterator<Map.Entry<String, Object>> iterator = paramMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Object> next = iterator.next();
postMethod.addParameter(next.getKey(), next.getValue().toString());
}
try {
int code = client.executeMethod(postMethod);
if (code == 200) {
res = postMethod.getResponseBodyAsString();
}
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
Get请求
String url = "请求路径如:http://xxx?name=zhangsan&age=18";
HttpClient httpClient = null;
HttpGet GetMethod = null;
HttpResponse response = null;
RebackTokenEntity rebackTokenEntity = null;
/*设置连接超时时间*/
RequestConfig requestConfig = RequestConfig.custom().
setConnectionRequestTimeout(10000).
setConnectTimeout(10000).
setSocketTimeout(10000).
build();
GetMethod.setConfig(requestConfig);
try {
httpClient = HttpClients.createDefault();
GetMethod = new HttpGet(url);//传入URL地址
//设置请求头
GetMethod.addHeader("Content-type", "application/json;charset=UTF-8");
response = httpClient.execute(GetMethod);//获取响应
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
System.out.println("HTTP请求未成功!HTTP Status Code:" + response.getStatusLine());
}
HttpEntity httpEntity = response.getEntity();
String reponseContent = EntityUtils.toString(httpEntity,"UTF-8");
EntityUtils.consume(httpEntity);//释放资源
Gson gson = new Gson();
Class= gson.fromJson(reponseContent, Class.class);
System.out.println("响应内容:" + reponseContent);
} catch (Exception e) {
e.printStackTrace();
}finally {
/*关闭连接资源*/
try {
if (response == null){
response.getEntity().getContent().close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
注:httpclient建立连接后主动close释放资源,避免thread pool is full
此处是抄袭原作者地址:
httpclient建立连接后主动close释放资源,避免thread pool is full
最近遇到线上机器的日志报错:error message:[]Error log: thread pool is full
定位原因是httpclient创建连接后没有及时关闭,为了关闭连接,特意找到了两种关闭连接的方法
方法1:关闭CloseableHttpResponse (推荐)
* Closes this stream and releases any system resources associated
* with it. If the stream is already closed then invoking this
* method has no effect.
close方法解释:关闭此流并释放与其关联的所有系统资源。 如果流已经关闭,则调用此方法无效
public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {
// 释放资源
if (httpResponse != null) {
httpResponse.close();
}
if (httpClient != null) {
httpClient.close();
}
}
方法2:不能直接close时,可使用response.getEntity().getContent().close()
可关闭此输入流并释放与该流关联的所有系统资源