官方文档地址:http://hc.apache.org/httpcomponents-client-4.5.x/quickstart.html
一、创建httpClient
1、请求中需要管理cookies,所以使用的不是createDefault(),而是costom()
public static BasicCookieStore cookieStore = new BasicCookieStore();
CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultCookieStore(cookieStore).build();
二、创建httpGet或HttpPost对象
1、GET方法:
HttpGet get = null;
if (param == null) {
get = new HttpGet(url);
}else {
get = new HttpGet(url + "?" + param);
2、POST方法:
HttpPost post = new HttpPost(url);
三、设置Header和超时时间,以及post的请求实体
1、Header设置(若post请求,则使用HttpPost对象调用setHeader()方法即可)
HttpGet get = new HttpGet(url);
get.setHeader("Accept-Encoding", "gzip, deflate, br");
get.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36");
2、超时设置(使用setConfig()方法,需要在方法中传RequestConfig类型参数)
RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(3000).build();
get.setConfig(config);
3、post请求实体(这里post中的参数param是String类型,form为“a=1&b=2”这种转换好的,若一个一个放则需要用StringEntity的子类UrlEncodedFormEntity)
StringEntity stringEntity = new StringEntity(param);
//JSONUtil是自己封装的关于json的类,isJSON(param)方法判断是否可解析成jsonObject格式
if (JSONUtil.isJSON(param)) {
stringEntity.setContentType("application/json");
}else {
stringEntity.setContentType("application/x-www-form-urlencoded");
}
post.setEntity(stringEntity);
注:content-type为form类型的一个一个添加参数方式:
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("username", "vip"));
nvps.add(new BasicNameValuePair("password", "secret"));
post.setEntity(new UrlEncodedFormEntity(nvps));
四、用httpClient执行httpGet/httpPost得到response
(若post请求,则在execute方法中传入HttpPost对象)
CloseableHttpResponse httpResponse = httpClient.execute(get);
五、从response中获取responseEntity
HttpEntity entity = httpResponse.getEntity();
String actResult = EntityUtils.toString(entity);
六、封装
(HttpGet和HttpPost是HttpRequestBase的子类,HttpRequestBase是HTTPMessage的子类,HttpRequestBase中有setConfig()方法,HTTPMessage有setHeader()方法)
package com.api.util;
import org.apache.http.HttpEntity;
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.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpUtil {
// 管理cookie的对象
public static BasicCookieStore cookieStore = new BasicCookieStore();
/**
* 设置请求头和超时
* @param httpRequestBase
* void
*
*/
public static void httpConfig(HttpRequestBase httpRequestBase){
httpRequestBase.setHeader("Accept-Encoding", "gzip, deflate, br");
httpRequestBase.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36");
RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(3000).build();
httpRequestBase.setConfig(config);
}
/**
* GET方法
* @param url
* @param param
* @return
* String
*
*/
public static String sendGet(String url,String param){
CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
// CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet get = null;
CloseableHttpResponse httpResponse = null;
String actResult = null;
try {
if (param == null) {
get = new HttpGet(url);
}else {
get = new HttpGet(url + "?" + param);
}
httpConfig(get);
httpResponse = httpClient.execute(get);
HttpEntity entity = httpResponse.getEntity();
actResult = EntityUtils.toString(entity);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
httpResponse.close();
httpClient.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
return actResult;
}
/**
* POST方法
* @param url
* @param param
* @return
* String
*
*/
public static String sendPost(String url,String param){
String actResult = null;
CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
// CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
CloseableHttpResponse httpResponse = null;
try {
httpConfig(post);
StringEntity stringEntity = new StringEntity(param);
if (JSONUtil.isJSON(param)) {
stringEntity.setContentType("application/json");
}else {
stringEntity.setContentType("application/x-www-form-urlencoded");
}
post.setEntity(stringEntity);
httpResponse = httpClient.execute(post);
HttpEntity entity = httpResponse.getEntity();
actResult = EntityUtils.toString(entity);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
httpResponse.close();
httpClient.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
return actResult;
}
}
网友评论