博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
HttpClient工具类
阅读量:4630 次
发布时间:2019-06-09

本文共 15782 字,大约阅读时间需要 52 分钟。

package com.wm.utils;import java.io.IOException;import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.Map.Entry;import org.apache.http.Header;import org.apache.http.HttpEntity;import org.apache.http.HttpHost;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.NameValuePair;import org.apache.http.auth.AuthScope;import org.apache.http.auth.UsernamePasswordCredentials;import org.apache.http.client.CredentialsProvider;import org.apache.http.client.config.RequestConfig;import org.apache.http.client.entity.GzipDecompressingEntity;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpDelete;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.client.methods.HttpPut;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.BasicCredentialsProvider;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.message.BasicNameValuePair;import org.apache.http.params.HttpConnectionParams;import org.apache.http.protocol.HTTP;import org.apache.http.util.EntityUtils;import common.util.ObjectUtil;/** * HttpClient工具类 */@SuppressWarnings("deprecation")public class HttpClientUtil {	public static String accept = "*/*";	public static String acceptEncoding = "gzip, deflate, sdch";	public static String acceptLanguage = "zh-CN,zh;q=0.8,en;q=0.6";	public static String connection = "keep-alive";	public static String contentType = "application/x-www-form-urlencoded";	public static String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2896.3 Safari/537.36";	public static int time_out = 30000;// 超时时间	public static boolean isGetSetCookie = false;// 是否获取set-cookie	public static String cookie = "";// set-cookie	public static String proxyIP = "";// 代理ip	public static int port = 0;// 端口号	public static String proxyUsername = "";// 代理账号	public static String proxyPassword = "";// 代理密码		/**	 * Get	 * 	 * @param url	 * @param charset	字符集。utf-8	 * @return	 */	public static String get(String url) {		// 关闭HttpClient系统日志;		System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");		System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");		System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "stdout");		HttpResponse response = null;		HttpEntity httpEntity = null;		String content = null;		try {//			CloseableHttpClient httpClient = HttpClients.createDefault();			CloseableHttpClient httpClient = HttpPoolManager.getHttpClient(); //http连接池			HttpGet get = new HttpGet(url);			// 请求头			get.addHeader("Accept", accept);			get.addHeader("Accept-Encoding", acceptEncoding);			get.addHeader("Accept-Language", acceptLanguage);			get.addHeader("Connection", connection);			get.addHeader("Content-Type", contentType);			get.addHeader("User-Agent", userAgent);			get.addHeader("cookie", cookie);			// 超时时间			get.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, time_out);// 设置连接超时时间			get.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, time_out);// 设置数据传输超时时间			// 设置代理			if(!StringUtil.isEmpty(proxyIP)) {				CredentialsProvider credsProvider = new BasicCredentialsProvider();				credsProvider.setCredentials(new AuthScope(proxyIP, port), new UsernamePasswordCredentials(proxyUsername, proxyPassword));				httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();				HttpHost proxy = new HttpHost(proxyIP, port);				RequestConfig config = RequestConfig.custom().setProxy(proxy).build();				get.setConfig(config);			}			// 执行请求			response = httpClient.execute(get);			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {				// 判断gzip,解压缩				if (!ObjectUtil.isEmpty(response.getLastHeader("Content-Encoding")) && (response.getLastHeader("Content-Encoding").toString()).indexOf("gzip") >= 0) {					response.setEntity(new GzipDecompressingEntity(response.getEntity()));				}				content = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);				if(isGetSetCookie){					Header[] cookieHeader = response.getHeaders("Set-Cookie");					if(null != cookieHeader && cookieHeader.length > 0){						cookie = cookieHeader[0].getValue();						isGetSetCookie = false;					}				}			}		} catch (Exception e) {			LogUtil.error("HttpClientUtil.get异常", e);		} finally {			if (null != httpEntity) {				try {					httpEntity.consumeContent();				} catch (IOException e) {					LogUtil.error("HttpClientUtil.get异常", e);				}			}		}		return content;	}	/**	 * Post	 * 	 * @param url	 * @param maps	参数组	 * @return	 */	public static String post(String url, Map
maps) { // 关闭HttpClient系统日志; System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true"); System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "stdout"); List
nvps = new ArrayList
(); for (Entry
map : maps.entrySet()) { nvps.add(new BasicNameValuePair(map.getKey(), map.getValue())); } String content = null; HttpResponse response = null; HttpEntity httpEntity = null; try {// CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpClient httpClient = HttpPoolManager.getHttpClient(); //http连接池 HttpPost post = new HttpPost(url); // 请求头 post.addHeader("Accept", accept); post.addHeader("Accept-Encoding", acceptEncoding); post.addHeader("Accept-Language", acceptLanguage); post.addHeader("Connection", connection); post.addHeader("Content-Type", contentType); post.addHeader("User-Agent", userAgent); post.addHeader("cookie", cookie); // 超时时间 post.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, time_out);// 设置连接超时时间 post.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, time_out);// 设置数据传输超时时间 // 设置代理 if(!StringUtil.isEmpty(proxyIP)) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(proxyIP, port), new UsernamePasswordCredentials(proxyUsername, proxyPassword)); httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); HttpHost proxy = new HttpHost(proxyIP, port); RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); post.setConfig(config); } // 执行请求 post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); response = httpClient.execute(post); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 判断gzip,解压缩 if (!ObjectUtil.isEmpty(response.getLastHeader("Content-Encoding")) && (response.getLastHeader("Content-Encoding").toString()).indexOf("gzip") >= 0) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); } httpEntity = response.getEntity(); content = EntityUtils.toString(httpEntity, HTTP.UTF_8); if(isGetSetCookie){ Header[] cookieHeader = response.getHeaders("Set-Cookie"); if(null != cookieHeader && cookieHeader.length > 0){ cookie = cookieHeader[0].getValue(); isGetSetCookie = false; } } } } catch (Exception e) { LogUtil.error("HttpClientUtil.post异常", e); } finally { if (null != httpEntity) { try { httpEntity.consumeContent(); } catch (IOException e) { LogUtil.error("HttpClientUtil.post异常", e); } } } return content; } /** * post流 * @param url * @param data * (以流的方式发送请求参数) * @return */ public static String postStream(String url, String data) { // 关闭HttpClient系统日志; System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true"); System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "stdout"); String content = null; HttpResponse response = null; HttpEntity httpEntity = null; try {// CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpClient httpClient = HttpPoolManager.getHttpClient(); //http连接池 HttpPost post = new HttpPost(url); // 请求头 post.addHeader("Accept", accept); post.addHeader("Accept-Encoding", acceptEncoding); post.addHeader("Accept-Language", acceptLanguage); post.addHeader("Connection", connection); post.addHeader("Content-Type", contentType); post.addHeader("User-Agent", userAgent); post.addHeader("cookie", cookie); // 超时时间 post.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, time_out);// 设置连接超时时间 post.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, time_out);// 设置数据传输超时时间 // 设置代理 if(!StringUtil.isEmpty(proxyIP)) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(proxyIP, port), new UsernamePasswordCredentials(proxyUsername, proxyPassword)); httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); HttpHost proxy = new HttpHost(proxyIP, port); RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); post.setConfig(config); } // 执行请求 StringEntity entity = new StringEntity(data, "UTF-8"); post.setEntity(entity); response = httpClient.execute(post); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 判断gzip,解压缩 if (!ObjectUtil.isEmpty(response.getLastHeader("Content-Encoding")) && (response.getLastHeader("Content-Encoding").toString()).indexOf("gzip") >= 0) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); } httpEntity = response.getEntity(); content = EntityUtils.toString(httpEntity, HTTP.UTF_8); if(isGetSetCookie){ Header[] cookieHeader = response.getHeaders("Set-Cookie"); if(null != cookieHeader && cookieHeader.length > 0){ cookie = cookieHeader[0].getValue(); isGetSetCookie = false; } } } } catch (Exception e) { LogUtil.error("HttpClientUtil.postStream异常", e); } finally { if (null != httpEntity) { try { httpEntity.consumeContent(); } catch (IOException e) { LogUtil.error("HttpClientUtil.postStream异常", e); } } } return content; } /** * Restful API Delete * @param url * @return */ public static String delete(String url){ // 关闭HttpClient系统日志; System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true"); System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "stdout"); HttpResponse response = null; HttpEntity httpEntity = null; String content = null; try { CloseableHttpClient httpClient = HttpPoolManager.getHttpClient(); //http连接池 HttpDelete delete = new HttpDelete(url); // 请求头 delete.addHeader("Accept", accept); delete.addHeader("Accept-Encoding", acceptEncoding); delete.addHeader("Accept-Language", acceptLanguage); delete.addHeader("Connection", connection); delete.addHeader("Content-Type", contentType); delete.addHeader("User-Agent", userAgent); delete.addHeader("cookie", cookie); // 超时时间 delete.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, time_out);// 设置连接超时时间 delete.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, time_out);// 设置数据传输超时时间 // 设置代理 if(!StringUtil.isEmpty(proxyIP)) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(proxyIP, port), new UsernamePasswordCredentials(proxyUsername, proxyPassword)); httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); HttpHost proxy = new HttpHost(proxyIP, port); RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); delete.setConfig(config); } // 执行请求 response = httpClient.execute(delete); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 判断gzip,解压缩 if (!ObjectUtil.isEmpty(response.getLastHeader("Content-Encoding")) && (response.getLastHeader("Content-Encoding").toString()).indexOf("gzip") >= 0) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); } content = EntityUtils.toString(response.getEntity(), HTTP.UTF_8); if(isGetSetCookie){ Header[] cookieHeader = response.getHeaders("Set-Cookie"); if(null != cookieHeader && cookieHeader.length > 0){ cookie = cookieHeader[0].getValue(); isGetSetCookie = false; } } } } catch (Exception e) { LogUtil.error("HttpClientUtil.delete异常", e); } finally { if (null != httpEntity) { try { httpEntity.consumeContent(); } catch (IOException e) { LogUtil.error("HttpClientUtil.delete异常", e); } } } return content; } /** * Restful API PUT * @param url * @param data * @return */ public static String putStream(String url, String data){ // 关闭HttpClient系统日志; System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true"); System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "stdout"); String content = null; HttpResponse response = null; HttpEntity httpEntity = null; try { CloseableHttpClient httpClient = HttpPoolManager.getHttpClient(); //http连接池 HttpPut put = new HttpPut(url); // 请求头 put.addHeader("Accept", accept); put.addHeader("Accept-Encoding", acceptEncoding); put.addHeader("Accept-Language", acceptLanguage); put.addHeader("Connection", connection); put.addHeader("Content-Type", contentType); put.addHeader("User-Agent", userAgent); put.addHeader("cookie", cookie); // 超时时间 put.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, time_out);// 设置连接超时时间 put.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, time_out);// 设置数据传输超时时间 // 设置代理 if(!StringUtil.isEmpty(proxyIP)) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(proxyIP, port), new UsernamePasswordCredentials(proxyUsername, proxyPassword)); httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); HttpHost proxy = new HttpHost(proxyIP, port); RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); put.setConfig(config); } // 执行请求 StringEntity entity = new StringEntity(data, "UTF-8"); put.setEntity(entity); response = httpClient.execute(put); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) { // 判断gzip,解压缩 if (!ObjectUtil.isEmpty(response.getLastHeader("Content-Encoding")) && (response.getLastHeader("Content-Encoding").toString()).indexOf("gzip") >= 0) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); } httpEntity = response.getEntity(); content = EntityUtils.toString(httpEntity, HTTP.UTF_8); if(isGetSetCookie){ Header[] cookieHeader = response.getHeaders("Set-Cookie"); if(null != cookieHeader && cookieHeader.length > 0){ cookie = cookieHeader[0].getValue(); isGetSetCookie = false; } } } } catch (Exception e) { LogUtil.error("HttpClientUtil.putStream异常", e); } finally { if (null != httpEntity) { try { httpEntity.consumeContent(); } catch (IOException e) { LogUtil.error("HttpClientUtil.putStream异常", e); } } } return content; } }

转载于:https://www.cnblogs.com/archermeng/p/7537050.html

你可能感兴趣的文章
关于 ListBox 自动换行
查看>>
poj3253
查看>>
CSS 和 JS 动画哪个更快
查看>>
postman测试上传文件
查看>>
R. ftp软件
查看>>
List<T>中,Remove和RemoveAt区别
查看>>
十月回家记
查看>>
ZOJ 3735 dp
查看>>
android效果背景虚化
查看>>
jQuery效果:隐藏、显示、切换、滑动、淡入淡出、动画
查看>>
Java 学习笔记(4)——java 常见类
查看>>
IOS开源项目汇总
查看>>
用herl工具解决微信内链接或二维码可直接用外部浏览器打开
查看>>
flex--unable to transcode image
查看>>
GITHup的使用
查看>>
void main()是错的!
查看>>
Atitit. Attilax企业框架 AEF的发展里程总结
查看>>
亚麻 面经_ml
查看>>
豆瓣api
查看>>
SQL数据库无法附加 系统表损坏修复 数据库中病毒解密恢复
查看>>