httpClient4请求工具类实现

package com.http;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class HttpClientUtil {

private static final String ENCODE = "UTF-8";

private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientUtil.class);

public static final Integer CONNECTION_TIMEOUT = 5000;

public static final Integer SO_TIMEOUT = 5000;

/**
 * get请求,参数拼接好
 * @Description TODO(描述)
 * @Author wangymd
 * @Date 2021-10-22 20:10:04 
 * @param url
 * @return
 *
 */
public static String get(String url) {
	try {
		HttpClient httpClient = new DefaultHttpClient();
		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT);
		
		HttpGet httpGet = new HttpGet(url);
		HttpResponse response = httpClient.execute(httpGet);
		if (null == response.getStatusLine() || 200 != response.getStatusLine().getStatusCode()) {
			return null;
		}
		
		HttpEntity entity = response.getEntity();
		return EntityUtils.toString(entity, ENCODE);
	} catch (Exception e) {
		LOGGER.error("get request error url:{}, e:{}",url, e);
	}
	return null;
}

/**
 * get请求url不带?
 * @Description TODO(描述)
 * @Author wangymd
 * @Date 2021-10-22 20:09:34 
 * @param url
 * @param params
 * @return
 *
 */
public static String get(String url, List<NameValuePair> params) {
	try {
		HttpClient httpClient = new DefaultHttpClient();
		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT);
		
		HttpGet httpGet = new HttpGet(url);
		
		//参数设置
		if(CollectionUtils.isNotEmpty(params)) {
			String paramStr = EntityUtils.toString(new UrlEncodedFormEntity(params));
			httpGet.setURI(new URI(httpGet.getURI().toString() + "?" + paramStr));
		}
        
		HttpResponse response = httpClient.execute(httpGet);
		if (null == response.getStatusLine() || 200 != response.getStatusLine().getStatusCode()) {
			return null;
		}
		
		HttpEntity entity = response.getEntity();
		return EntityUtils.toString(entity, ENCODE);
	} catch (Exception e) {
		LOGGER.error("get request error url:{}, timeout:{}, e:{}",url, JSON.toJSONString(params), e);
	}
	return null;
}

/**
 * post请求json参数
 * @Description TODO(描述)
 * @Author wangymd
 * @Date 2021-10-22 20:06:20 
 * @param url
 * @param params
 * @return
 *
 */
public static String post(String url, List<NameValuePair> params) {
	try {
		HttpClient httpClient = new DefaultHttpClient();
		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT);
		
		HttpPost httpPost = new HttpPost(url);
		httpPost.setHeader("Content-type", "application/json;charset=utf-8");
		httpPost.setHeader("Connection", "Close");
		
		//参数设置
		JSONObject jsonObject = new JSONObject();
		if(CollectionUtils.isNotEmpty(params)) {
			for (NameValuePair nameValuePair : params) {
				jsonObject.put(nameValuePair.getName(), nameValuePair.getValue());
			}
		}
		StringEntity stringEntity = new StringEntity(jsonObject.toJSONString());
		stringEntity.setContentType("application/json");
		stringEntity.setContentEncoding(ENCODE);
		httpPost.setEntity(stringEntity);
		
		HttpResponse response = httpClient.execute(httpPost);
		if (null == response.getStatusLine() || 200 != response.getStatusLine().getStatusCode()) {
			return null;
		}
		
		HttpEntity entity = response.getEntity();
		return EntityUtils.toString(entity, ENCODE);
	} catch (Exception e) {
		LOGGER.error("post request error url:{}, timeout:{}, e:{}",url, JSON.toJSONString(params), e);
	}
	return null;
}

/**
 * 测试
 * @Description TODO(描述)
 * @Author wangymd
 * @Date 2021-10-20 11:17:26 
 * @param args
 * @throws Exception
 *
 */
  public static void main(String[] args) throws Exception {
	  String accesstoken = "xxxxxx";
		List<NameValuePair> nvps = new ArrayList <NameValuePair>();
		nvps.add(new BasicNameValuePair("p1", "p1"));
		nvps.add(new BasicNameValuePair("p2", "p2"));

		String result = HttpClientUtil.post("https://api.weixin.qq.com/mmec/api/XXXX?access_token=" + accesstoken, nvps);
  
      System.out.println(result);
  }

}

上一篇:《C# GDI+ 破境之道》:第一境 GDI+基础 —— 第三节:画圆形


下一篇:【nginx】基于域名的nginx虚拟机主机