httpClient4请求工具类实现

发布时间:2022-07-02 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了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);
  }

}

脚本宝典总结

以上是脚本宝典为你收集整理的httpClient4请求工具类实现全部内容,希望文章能够帮你解决httpClient4请求工具类实现所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: