HttpClient的get+post请求使用

时间:2023-03-08 21:05:46

啥都不说,先上代码

 import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.HttpRequestBase;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger; import com.alibaba.fastjson.JSONObject; /**
* http请求工具类
* Created by swordxu on 15/8/5.
*/
public class HttpClientUtils {
private static Logger logger = Logger.getLogger(HttpClientUtils.class); //设置连接池线程最大数量
private static final int MAX_TOTAL = 500;
//设置单个路由最大的连接线程数量
private static final int MAX_ROUTE_TOTAL = 500; private static final int REQUEST_TIMEOUT = 25000; private static final int REQUEST_SOCKET_TIME = 25000; private static final String ENCODING_UTF_8 = "UTF-8"; private static HttpClientBuilder httpBulder = null;
private static CloseableHttpClient httpClient = null; static{ if (httpClient == null) {
ConnectionSocketFactory httpFactory = PlainConnectionSocketFactory.getSocketFactory(); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create().register("http", httpFactory).build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
cm.setMaxTotal(MAX_TOTAL); cm.setDefaultMaxPerRoute(MAX_ROUTE_TOTAL); httpClient = HttpClients.custom().setConnectionManager(cm)
.disableAutomaticRetries().build();
} } /**
* get请求方式
* @param uri 请求url
* @return
*/
public String doGet(String uri) throws Exception{
long b = System.currentTimeMillis();
//CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpGet httpget = null;
try {
logger.debug("executing get request uri :" + uri); httpget = new HttpGet(uri);
//httpClient = HttpClients.createDefault();
response = httpClient.execute(httpget); if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity entity = response.getEntity();
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), ENCODING_UTF_8));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
logger.debug("response body :" + sb);
long e = System.currentTimeMillis();
logger.debug("executing post request time:" + (e -b)); EntityUtils.consume(entity);//关闭httpEntity流 return sb.toString();
}else{
throw new Exception(response.getStatusLine().getStatusCode()+"");
}
} catch (ClientProtocolException e) {
logger.error("Failed to get request uri: "+uri,e);
throw new RuntimeException("Failed to post request uri: "+uri,e);
} catch (IOException e) {
logger.error("Failed to get request uri: "+uri,e);
throw new RuntimeException("Failed to post request uri: "+uri,e);
}finally {
close(httpget,response);
}
}
/**
* post 请求并返回实体对象
* @param url 请求url
* @param paramaters 请求参数
* @param clazz 返回Class
* @return
* @throws Exception
*/
public static <T> T doPost(String url, Map<String, String> paramaters,Class<T> clazz) throws Exception{
String ret = post(url, paramaters, null);
return null != ret ? JSONObject.parseObject(ret, clazz) : null;
} /**
* 发送POST请求
* @param uri
* @return
*/
public static String post(String uri) throws Exception{
return post(uri, null);
} /**
* 发送POST请求
* @param uri
* @param paramMap 请求参数
* @return
*/
public static String post(String uri, Map<String, String> paramMap) throws Exception{
return post(uri, paramMap, null);
} /**
* post 请求
* @param uri 请求url
* @param paramMap 请求参数
* @param charset 请求编码
* @return
* @throws Exception
*/
public static String post(String uri, Map<String, String> paramMap,String charset) throws Exception{
long b = System.currentTimeMillis();
CloseableHttpResponse response = null;
//CloseableHttpClient httpClient = null;
HttpPost httpPost = null;
try {
logger.debug("executing post request url:"+uri); httpPost = new HttpPost(uri);
httpPost.setEntity(new UrlEncodedFormEntity(handleData(paramMap),null == charset ? ENCODING_UTF_8 : charset)); //httpClient = HttpClients.createDefault();
response = httpClient.execute(httpPost);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity entity = response.getEntity();
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), ENCODING_UTF_8));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
logger.debug("response body :" + sb);
long e = System.currentTimeMillis();
logger.debug("executing post request time:" + (e -b)); EntityUtils.consume(entity);//关闭流 return sb.toString();
}else{
throw new Exception(response.getStatusLine().getStatusCode()+"");
}
} catch (Exception e) {
throw e;
}finally{
close(httpPost,response);
}
} /**
* post 请求
* @param url
* @param params
* @return
*/
public static String doPost(String url, Map<String, String> params) throws Exception{
return post(url, params, null);
} /**
* post 请求
* @param url
* @param json
* @return
*/
public static <T> T doPost(String url, String json, Class<T> clazz) throws Exception{
String ret = doPost(url, json);
return null != ret ? JSONObject.parseObject(ret, clazz) : null;
} /**
* post 请求
* @param url
* @param json
* @return
*/
public static String doPost(String url, String json) throws Exception{
CloseableHttpResponse response = null;
HttpPost httpPost = null;
long b = System.currentTimeMillis();
try {
logger.debug("executing post request url:" + url); StringEntity s = new StringEntity(json,"UTF-8");
s.setContentType("application/json"); httpPost = new HttpPost(url);
httpPost.setEntity(s); //httpClient = HttpClients.createDefault();
response = httpClient.execute(httpPost); if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity entity = response.getEntity();
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), ENCODING_UTF_8));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
logger.debug("response body :" + sb);
long e = System.currentTimeMillis();
logger.debug("executing post request time:" + (e -b)); EntityUtils.consume(entity);//关闭流 return sb.toString();
}else{
throw new Exception(response.getStatusLine().getStatusCode()+"");
}
}finally{
close(httpPost,response);
}
} /**
* 处理map数据
* @param postData 请求数据
* @return
*/
private static List<NameValuePair> handleData(Map<String, String> postData) {
List<NameValuePair> datas = new ArrayList<NameValuePair>();
for (Map.Entry<String,String> entry : postData.entrySet()) {
datas.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
return datas;
}
/**
* 关闭链接
* @param request
* @param response
*/
private static void close(HttpRequestBase request,CloseableHttpResponse response){
if(null != response){
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(null != request){
request.releaseConnection();
}
}

1、http的静态变量的相关设置

static{

        if (httpClient == null) {
ConnectionSocketFactory httpFactory = PlainConnectionSocketFactory.getSocketFactory(); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create().register("http", httpFactory).build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
cm.setMaxTotal(MAX_TOTAL); cm.setDefaultMaxPerRoute(MAX_ROUTE_TOTAL); httpClient = HttpClients.custom().setConnectionManager(cm)
.disableAutomaticRetries().build();
} }

2.httpCliet的调用

String strResult = "";
JSONObject jobj = new JSONObject();
jobj.put("wxacc", wxacc);
jobj.put("password", password);
jobj.put("smallClassId", smallClassId);
jobj.put("reportName", reportName);
jobj.put("mobile", mobile);
jobj.put("address", address);
jobj.put("description", description);
jobj.put("position", position);
jobj.put("files", files);
jobj.put("wxEvtFileList", wxEvtFileList);
jobj.put("isreceipt", "true"); String conResult;
try {
conResult = HttpClientUtils.doPost(saveEvtPreUrl, jobj.toJSONString());
Head head = JSON.parseObject(conResult, Head.class);
logger.debug(head.toString());
} catch (Exception e) {
e.printStackTrace();
} return strResult;

 完~