博客详情

HttpClientUtil (原创)

作者: 朝如青丝暮成雪
发布时间:2019-10-18 11:55:01  文章分类:java编程   阅读(979)  评论(0)

pom.xml配置:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.6</version> 
</dependency>


HttpClientUtil.java


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClientUtil {

	/**
	 * 发送http get请求
	 * @param url
	 * @return
	 */
	public static String httpGet(String url) {
		CloseableHttpClient client = null;
		HttpGet httpGet = null;
		try {
			client = HttpClients.createDefault();
			httpGet = new HttpGet(url); // get请求
			httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0");
			// 设置请求和传输超时时间
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
			httpGet.setConfig(requestConfig);
			CloseableHttpResponse response = client.execute(httpGet);
			// 请求发送成功,并得到响应
			// 读取服务器返回过来的json字符串数据
			HttpEntity entity = response.getEntity();
			return EntityUtils.toString(entity, "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			if (httpGet != null) {
				httpGet.releaseConnection();
			}
			if (client != null) {
				try {
					client.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 发送http post请求
	 * @param url
	 * @param params
	 * @return
	 */
	public static String httpPost(String url, Map<String, Object> params) {
		CloseableHttpClient client = null;
		HttpPost httpPost = null;
		try {
			client = HttpClients.createDefault();
			httpPost = new HttpPost(url);
			httpPost.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0");
			httpPost.setHeader("Content-Type","application/x-www-form-urlencoded");//表单
		 
			// 设置请求和传输超时时间
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
			httpPost.setConfig(requestConfig);
			// 封装form参数 key-value
			List<NameValuePair> formParams = new ArrayList<NameValuePair>();
			if (params != null && params.size() > 0) {
				for (Map.Entry<String, Object> entry : params.entrySet()) {
					formParams.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
				}
			}
			UrlEncodedFormEntity urlEntity = new UrlEncodedFormEntity(formParams, "UTF-8");
            httpPost.setEntity(urlEntity);
            HttpResponse   response = client.execute(httpPost);
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			if (httpPost != null) {
				httpPost.releaseConnection();
			}
			if (client != null) {
				try {
					client.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 发送json post请求
	 * @param url
	 * @param jsonStr
	 * @param customHeaders 自定义请求头 ,如Authorization
	 * @return
	 */
	public static   String  jsonPost(String url ,String jsonStr,NameValuePair... customHeaders) {
		CloseableHttpClient client = null;
		HttpPost httpPost = null;
		try {
			client = HttpClients.createDefault();
			httpPost = new HttpPost(url);
			httpPost.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0");
		    httpPost.setHeader("Content-Type", "application/json");
		    for(NameValuePair  kv: customHeaders) {
		    	httpPost.setHeader(kv.getName(), kv.getValue());
		    }
			// 设置请求和传输超时时间
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
			httpPost.setConfig(requestConfig);
			if ( jsonStr!=null) {
				StringEntity entity = new StringEntity(jsonStr, "utf-8");
				httpPost.setEntity(entity);
			}
            HttpResponse   response = client.execute(httpPost);
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			if (httpPost != null) {
				httpPost.releaseConnection();
			}
			if (client != null) {
				try {
					client.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
 
}



关键字:  httpclient
评论信息
暂无评论
发表评论

亲,您还没有登陆,暂不能评论哦! 去 登陆 | 注册

博主信息
   
数据加载中,请稍候...
文章分类
   
数据加载中,请稍候...
阅读排行
 
数据加载中,请稍候...
评论排行
 
数据加载中,请稍候...

Copyright © 叮叮声的奶酪 版权所有
备案号:鄂ICP备17018671号-1

鄂公网安备 42011102000739号