http工具类_http请求工具类 - CSDN
精华内容
参与话题
  • HTTPClient工具类,完整

    2020-07-29 14:20:11
    HTTPClient工具类,完整,HTTPClient工具类,完整,HTTPClient工具类,完整HTTPClient工具类,完整,HTTPClient工具类,完整
  • httpclient封装工具类

    万次阅读 2019-09-05 22:55:36
    前言在日常开发中,我们经常需要通过http协议去调用网络内容,虽然java自身提供了net相关工具包,但是其灵活性和功能总是不如人意,...在项目中对于这个工具类库也许没有进行很好的封装。在哪里使用就写在哪些,很多

    ##前言##
    在日常开发中,我们经常需要通过http协议去调用网络内容,虽然java自身提供了net相关工具包,但是其灵活性和功能总是不如人意,于是有人专门搞出一个httpclient类库,来方便进行Http操作。对于httpcore的源码研究,我们可能并没有达到这种层次,在日常开发中也只是需要的时候,在网上百度一下,然后进行调用就行。在项目中对于这个工具类库也许没有进行很好的封装。在哪里使用就写在哪些,很多地方用到,就在多个地方写。反正是复制粘贴,很方便,但是这样就会导致项目中代码冗余。所以这里简单的对httpcient的简单操作封装成一个工具类,统一放在项目的工具包中,在使用的时候直接从工具包中调用,不需要写冗余代码。

    httpclient操作实例

    首先需要在注意的一点是,这是基于httpclient4.5版本的,我们在使用的时候需要引入具体对应jar。下面是具体代码示例

    import java.io.IOException;
    import java.security.KeyManagementException;
    import java.security.KeyStoreException;
    import java.security.NoSuchAlgorithmException;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    
    import javax.net.ssl.SSLContext;
    
    import org.apache.commons.lang3.StringUtils;
    import org.apache.http.HttpEntity;
    import org.apache.http.NameValuePair;
    import org.apache.http.ParseException;
    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.conn.ssl.SSLConnectionSocketFactory;
    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.message.BasicNameValuePair;
    import org.apache.http.ssl.SSLContextBuilder;
    import org.apache.http.ssl.TrustStrategy;
    import org.apache.http.util.EntityUtils;
    
    /**
     * 基于 httpclient 4.5版本的 http工具类
     * 
     * @author 爱琴孩
     * 
     */
    public class HttpClientTool {
    
    	private static final CloseableHttpClient httpClient;
    	public static final String CHARSET = "UTF-8";
    	// 采用静态代码块,初始化超时时间配置,再根据配置生成默认httpClient对象
    	static {
    		RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build();
    		httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
    	}
    
    	public static String doGet(String url, Map<String, String> params) {
    		return doGet(url, params, CHARSET);
    	}
    
    	public static String doGetSSL(String url, Map<String, String> params) {
    		return doGetSSL(url, params, CHARSET);
    	}
    
    	public static String doPost(String url, Map<String, String> params) throws IOException {
    		return doPost(url, params, CHARSET);
    	}
    
    	/**
    	 * HTTP Get 获取内容
    	 * @param url 请求的url地址 ?之前的地址
    	 * @param params 请求的参数
    	 * @param charset 编码格式
    	 * @return 页面内容
    	 */
    	public static String doGet(String url, Map<String, String> params, String charset) {
    		if (StringUtils.isBlank(url)) {
    			return null;
    		}
    		try {
    			if (params != null && !params.isEmpty()) {
    				List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
    				for (Map.Entry<String, String> entry : params.entrySet()) {
    					String value = entry.getValue();
    					if (value != null) {
    						pairs.add(new BasicNameValuePair(entry.getKey(), value));
    					}
    				}
    				// 将请求参数和url进行拼接
    				url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
    			}
    			HttpGet httpGet = new HttpGet(url);
    			CloseableHttpResponse response = httpClient.execute(httpGet);
    			int statusCode = response.getStatusLine().getStatusCode();
    			if (statusCode != 200) {
    				httpGet.abort();
    				throw new RuntimeException("HttpClient,error status code :" + statusCode);
    			}
    			HttpEntity entity = response.getEntity();
    			String result = null;
    			if (entity != null) {
    				result = EntityUtils.toString(entity, "utf-8");
    			}
    			EntityUtils.consume(entity);
    			response.close();
    			return result;
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		return null;
    	}
    
    	/**
    	 * HTTP Post 获取内容
    	 * @param url 请求的url地址 ?之前的地址
    	 * @param params 请求的参数
    	 * @param charset 编码格式
    	 * @return 页面内容
    	 * @throws IOException
    	 */
    	public static String doPost(String url, Map<String, String> params, String charset) 
    			throws IOException {
    		if (StringUtils.isBlank(url)) {
    			return null;
    		}
    		List<NameValuePair> pairs = null;
    		if (params != null && !params.isEmpty()) {
    			pairs = new ArrayList<NameValuePair>(params.size());
    			for (Map.Entry<String, String> entry : params.entrySet()) {
    				String value = entry.getValue();
    				if (value != null) {
    					pairs.add(new BasicNameValuePair(entry.getKey(), value));
    				}
    			}
    		}
    		HttpPost httpPost = new HttpPost(url);
    		if (pairs != null && pairs.size() > 0) {
    			httpPost.setEntity(new UrlEncodedFormEntity(pairs, CHARSET));
    		}
    		CloseableHttpResponse response = null;
    		try {
    			response = httpClient.execute(httpPost);
    			int statusCode = response.getStatusLine().getStatusCode();
    			if (statusCode != 200) {
    				httpPost.abort();
    				throw new RuntimeException("HttpClient,error status code :" + statusCode);
    			}
    			HttpEntity entity = response.getEntity();
    			String result = null;
    			if (entity != null) {
    				result = EntityUtils.toString(entity, "utf-8");
    			}
    			EntityUtils.consume(entity);
    			return result;
    		} catch (ParseException e) {
    			e.printStackTrace();
    		} finally {
    			if (response != null)
    				response.close();
    		}
    		return null;
    	}
    
    	/**
    	 * HTTPS Get 获取内容
    	 * @param url 请求的url地址 ?之前的地址
    	 * @param params 请求的参数
    	 * @param charset  编码格式
    	 * @return 页面内容
    	 */
    	public static String doGetSSL(String url, Map<String, String> params, String charset) {
    		if (StringUtils.isBlank(url)) {
    			return null;
    		}
    		try {
    			if (params != null && !params.isEmpty()) {
    				List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
    				for (Map.Entry<String, String> entry : params.entrySet()) {
    					String value = entry.getValue();
    					if (value != null) {
    						pairs.add(new BasicNameValuePair(entry.getKey(), value));
    					}
    				}
    				url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
    			}
    			HttpGet httpGet = new HttpGet(url);
    
    			// https  注意这里获取https内容,使用了忽略证书的方式,当然还有其他的方式来获取https内容
    			CloseableHttpClient httpsClient = HttpClientTool.createSSLClientDefault();
    			CloseableHttpResponse response = httpsClient.execute(httpGet);
    			int statusCode = response.getStatusLine().getStatusCode();
    			if (statusCode != 200) {
    				httpGet.abort();
    				throw new RuntimeException("HttpClient,error status code :" + statusCode);
    			}
    			HttpEntity entity = response.getEntity();
    			String result = null;
    			if (entity != null) {
    				result = EntityUtils.toString(entity, "utf-8");
    			}
    			EntityUtils.consume(entity);
    			response.close();
    			return result;
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		return null;
    	}
    	
    	/**
    	 * 这里创建了忽略整数验证的CloseableHttpClient对象
    	 * @return
    	 */
    	public static CloseableHttpClient createSSLClientDefault() {
    		try {
    			SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
    				// 信任所有
    				public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    					return true;
    				}
    			}).build();
    			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
    			return HttpClients.custom().setSSLSocketFactory(sslsf).build();
    		} catch (KeyManagementException e) {
    			e.printStackTrace();
    		} catch (NoSuchAlgorithmException e) {
    			e.printStackTrace();
    		} catch (KeyStoreException e) {
    			e.printStackTrace();
    		}
    		return HttpClients.createDefault();
    	}
    }
    

    总结

    上面就是对于httpclient的简单工具类,对于httpclient,还有很多知识点需要仔细研究,后面再和大家一起来总结学习!

    展开全文
  • Http工具类

    2019-02-28 09:04:32
    package ... import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http....
    package com.test.third.utils;
    
    import org.apache.commons.io.IOUtils;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.HttpStatus;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.HttpClient;
    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.conn.ssl.SSLConnectionSocketFactory;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.DefaultHttpClient;
    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 javax.net.ssl.SSLContext;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.X509TrustManager;
    import java.io.IOException;
    import java.io.InputStream;
    import java.nio.charset.Charset;
    import java.security.KeyManagementException;
    import java.security.NoSuchAlgorithmException;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    import java.text.SimpleDateFormat;
    import java.util.*;
    
    /**
     * HTTP 请求工具类
     */
    public class HttpUtils {
    	private static PoolingHttpClientConnectionManager connMgr;
    	private static RequestConfig requestConfig;
    	private static final int MAX_TIMEOUT = 20000;
    
    	static {
    		// 设置连接池
    		connMgr = new PoolingHttpClientConnectionManager();
    		// 设置连接池大小
    		connMgr.setMaxTotal(100);
    		connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
    
    		RequestConfig.Builder configBuilder = RequestConfig.custom();
    		// 设置连接超时
    		configBuilder.setConnectTimeout(MAX_TIMEOUT);
    		// 设置读取超时
    		configBuilder.setSocketTimeout(MAX_TIMEOUT);
    		// 设置从连接池获取连接实例的超时
    		configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
    		// 在提交请求之前 测试连接是否可用
    		configBuilder.setStaleConnectionCheckEnabled(true);
    		requestConfig = configBuilder.build();
    	}
    
    	/**
    	 * 发送 GET 请求(HTTP),不带输入数据
    	 * 
    	 * @param url
    	 * @param headers
    	 *            需要添加的httpheader参数
    	 * @return
    	 */
    	public static String doGet(String url, Map<String, String> headers, Map<String, Object> params) {
    
    		if (url.startsWith("https://")) {
    			return doGetSSL(url, headers, params);
    		} else {
    			return doGetHttp(url, headers, params);
    		}
    
    	}
    
    	/**
    	 * 发送 GET 请求(HTTP),K-V形式
    	 * 
    	 * @param url
    	 * @param headers
    	 *            需要添加的httpheader参数
    	 * @param params
    	 * @return
    	 */
    	public static String doGetHttp(String url, Map<String, String> headers, Map<String, Object> params) {
    		HttpClient httpclient = new DefaultHttpClient();
    		String apiUrl = url;
    		StringBuffer param = new StringBuffer();
    		int i = 0;
    		for (String key : params.keySet()) {
    			if (i == 0)
    				param.append("?");
    			else
    				param.append("&");
    			param.append(key).append("=").append(params.get(key));
    			i++;
    		}
    		apiUrl += param;
    		String result = null;
    		log("url: " + apiUrl);
    		try {
    			HttpGet httpGet = new HttpGet(apiUrl);
    			// 添加http headers
    			if (headers != null && headers.size() > 0) {
    				for (String key : headers.keySet()) {
    					httpGet.addHeader(key, headers.get(key));
    				}
    			}
    
    			HttpResponse response = httpclient.execute(httpGet);
    			int statusCode = response.getStatusLine().getStatusCode();
    
    			log("code : " + statusCode);
    
    			HttpEntity entity = response.getEntity();
    			if (entity != null) {
    				InputStream instream = entity.getContent();
    				result = IOUtils.toString(instream, "UTF-8");
    			}
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		return result;
    	}
    
    	/**
    	 * 发送 SSL Get 请求(HTTPS),K-V形式
    	 * 
    	 * @param
    	 *            API接口URL
    	 * @param headers
    	 * @param params
    	 *            参数map
    	 * @return
    	 */
    	public static String doGetSSL(String url, Map<String, String> headers, Map<String, Object> params) {
    		CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())
    				.setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
    		CloseableHttpResponse response = null;
    		String apiUrl = url;
    		String httpStr = null;
    		StringBuffer param = new StringBuffer();
    		int i = 0;
    		for (String key : params.keySet()) {
    			if (i == 0)
    				param.append("?");
    			else
    				param.append("&");
    			param.append(key).append("=").append(params.get(key));
    			i++;
    		}
    		apiUrl += param;
    		log("url: " + apiUrl);
    
    		try {
    			HttpGet httpGet = new HttpGet(apiUrl);
    			httpGet.setConfig(requestConfig);
    			// 添加http headers
    			if (headers != null && headers.size() > 0) {
    				for (String key : headers.keySet()) {
    					httpGet.addHeader(key, headers.get(key));
    				}
    			}
    			response = httpClient.execute(httpGet);
    			int statusCode = response.getStatusLine().getStatusCode();
    			log("code : " + statusCode);
    			if (statusCode != HttpStatus.SC_OK) {
    				return null;
    			}
    			HttpEntity entity = response.getEntity();
    			if (entity == null) {
    				return null;
    			}
    			httpStr = EntityUtils.toString(entity, "utf-8");
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			if (response != null) {
    				try {
    					EntityUtils.consume(response.getEntity());
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    		return httpStr;
    
    	}
    
    	/**
    	 * 发送 POST 请求(HTTP),K-V形式
    	 * 
    	 * @param url
    	 * @param headers
    	 *            需要添加的httpheader参数
    	 * @return
    	 */
    	public static String doPostByForm(String url, Map<String, String> headers, Map<String, Object> params) {
    		if (url.startsWith("https://")) {
    			return doPostSSL(url, headers, params);
    		} else {
    			return doPostHttp(url, headers, params);
    		}
    
    	}
    	
    	/**
    	 * 发送 POST 请求(HTTP),JSON形式
    	 * 
    	 * @param url
    	 * @param headers
    	 *            需要添加的httpheader参数
    	 * @return
    	 */
    	public static String doPostByJson(String url, Map<String, String> headers, Object json) {
    		if (url.startsWith("https://")) {
    			return doPostSSL(url, headers, json);
    		} else {
    			return doPostHttp(url, headers, json);
    		}
    
    	}
    
    	/**
    	 * 发送 POST 请求(HTTP),K-V形式
    	 * 
    	 * @param apiUrl
    	 *            API接口URL
    	 * @param headers
    	 *            需要添加的httpheader参数
    	 * @param params
    	 *            参数map
    	 * @return
    	 */
    	public static String doPostHttp(String apiUrl, Map<String, String> headers, Map<String, Object> params) {
    		CloseableHttpClient httpClient = HttpClients.createDefault();
    		String httpStr = null;
    		HttpPost httpPost = new HttpPost(apiUrl);
    		CloseableHttpResponse response = null;
    		if (headers != null) {
    			Set<String> keys = headers.keySet();
    			for (Iterator<String> i = keys.iterator(); i.hasNext();) {
    				String key = (String) i.next();
    				httpPost.addHeader(key, headers.get(key));
    			}
    		}
    		try {
    			httpPost.setConfig(requestConfig);
    			List<NameValuePair> pairList = new ArrayList<>(params.size());
    			for (Map.Entry<String, Object> entry : params.entrySet()) {
    				NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
    				pairList.add(pair);
    			}
    			httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
    			response = httpClient.execute(httpPost);
    			log(response.toString());
    			HttpEntity entity = response.getEntity();
    			httpStr = EntityUtils.toString(entity, "UTF-8");
    		} catch (IOException e) {
    			e.printStackTrace();
    		} finally {
    			if (response != null) {
    				try {
    					EntityUtils.consume(response.getEntity());
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    		return httpStr;
    	}
    
    	/**
    	 * 发送 POST 请求(HTTP),JSON形式
    	 * 
    	 * @param apiUrl
    	 * @param headers
    	 *            需要添加的httpheader参数
    	 * @param json
    	 *            json对象
    	 * @return
    	 */
    	public static String doPostHttp(String apiUrl, Map<String, String> headers, Object json) {
    		CloseableHttpClient httpClient = HttpClients.createDefault();
    		String httpStr = null;
    		HttpPost httpPost = new HttpPost(apiUrl);
    		CloseableHttpResponse response = null;
    		if (headers != null) {
    			Set<String> keys = headers.keySet();
    			for (Iterator<String> i = keys.iterator(); i.hasNext();) {
    				String key = (String) i.next();
    				httpPost.addHeader(key, headers.get(key));
    
    			}
    		}
    		try {
    			httpPost.setConfig(requestConfig);
    			StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");// 解决中文乱码问题
    			stringEntity.setContentEncoding("UTF-8");
    			stringEntity.setContentType("application/json");
    			httpPost.setEntity(stringEntity);
    			response = httpClient.execute(httpPost);
    			HttpEntity entity = response.getEntity();
    			log(response.getStatusLine().getStatusCode() + "");
    			httpStr = EntityUtils.toString(entity, "UTF-8");
    		} catch (IOException e) {
    			e.printStackTrace();
    		} finally {
    			if (response != null) {
    				try {
    					EntityUtils.consume(response.getEntity());
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    		return httpStr;
    	}
    
    	/**
    	 * 发送 SSL POST 请求(HTTPS),K-V形式
    	 * 
    	 * @param apiUrl
    	 *            API接口URL
    	 * @param params
    	 *            参数map
    	 * @return
    	 */
    	public static String doPostSSL(String apiUrl, Map<String, String> headers, Map<String, Object> params) {
    		CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())
    				.setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
    		HttpPost httpPost = new HttpPost(apiUrl);
    		CloseableHttpResponse response = null;
    		String httpStr = null;
    		if (headers != null) {
    			Set<String> keys = headers.keySet();
    			for (Iterator<String> i = keys.iterator(); i.hasNext();) {
    				String key = (String) i.next();
    				httpPost.addHeader(key, headers.get(key));
    
    			}
    		}
    		try {
    			httpPost.setConfig(requestConfig);
    			List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());
    			for (Map.Entry<String, Object> entry : params.entrySet()) {
    				NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
    				pairList.add(pair);
    			}
    			httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("utf-8")));
    			response = httpClient.execute(httpPost);
    			int statusCode = response.getStatusLine().getStatusCode();
    			if (statusCode != HttpStatus.SC_OK) {
    				return null;
    			}
    			HttpEntity entity = response.getEntity();
    			if (entity == null) {
    				return null;
    			}
    			httpStr = EntityUtils.toString(entity, "utf-8");
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			if (response != null) {
    				try {
    					EntityUtils.consume(response.getEntity());
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    		return httpStr;
    	}
    
    	/**
    	 * 发送 SSL POST 请求(HTTPS),JSON形式
    	 * 
    	 * @param apiUrl
    	 *            API接口URL
    	 * @param json
    	 *            JSON对象
    	 * @return
    	 */
    	public static String doPostSSL(String apiUrl, Map<String, String> headers, Object json) {
    		CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())
    				.setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
    		HttpPost httpPost = new HttpPost(apiUrl);
    		CloseableHttpResponse response = null;
    		String httpStr = null;
    		if (headers != null) {
    			Set<String> keys = headers.keySet();
    			for (Iterator<String> i = keys.iterator(); i.hasNext();) {
    				String key = (String) i.next();
    				httpPost.addHeader(key, headers.get(key));
    
    			}
    		}
    		try {
    			httpPost.setConfig(requestConfig);
    			StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");// 解决中文乱码问题
    			stringEntity.setContentEncoding("UTF-8");
    			stringEntity.setContentType("application/json");
    			httpPost.setEntity(stringEntity);
    			response = httpClient.execute(httpPost);
    			int statusCode = response.getStatusLine().getStatusCode();
    			if (statusCode != HttpStatus.SC_OK) {
    				return null;
    			}
    			HttpEntity entity = response.getEntity();
    			if (entity == null) {
    				return null;
    			}
    			httpStr = EntityUtils.toString(entity, "utf-8");
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			if (response != null) {
    				try {
    					EntityUtils.consume(response.getEntity());
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    		return httpStr;
    	}
    
    	/**
    	 * 创建SSL安全连接
    	 *
    	 * @return
    	 * @throws NoSuchAlgorithmException
    	 * @throws KeyManagementException
    	 */
    	private static SSLConnectionSocketFactory createSSLConnSocketFactory() {
    		// 创建TrustManager
    		X509TrustManager xtm = new X509TrustManager() {
    			public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    			}
    
    			public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    			}
    
    			public X509Certificate[] getAcceptedIssuers() {
    				return null;
    			}
    		};
    		// TLS1.0与SSL3.0基本上没有太大的差别,可粗略理解为TLS是SSL的继承者,但它们使用的是相同的SSLContext
    		SSLContext ctx;
    		try {
    			ctx = SSLContext.getInstance("TLS");
    			// 使用TrustManager来初始化该上下文,TrustManager只是被SSL的Socket所使用
    			ctx.init(null, new TrustManager[] { xtm }, null);
    			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ctx);
    			return sslsf;
    		} catch (NoSuchAlgorithmException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (KeyManagementException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		return null;
    	}
    
    	public static void log(String msg) {
    		System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\t: " + msg);
    	}
    
    	/**
    	 * 测试方法
    	 * 
    	 * @param args
    	 */
    	public static void main(String[] args) throws Exception {
    
    	}
    }

     

    展开全文
  • 在项目开发中,经常用调用http接口,下面是封装apache的httpclient工具类。 二、样例代码: package org.egg.utils; import org.apache.http.client.config.RequestConfig; import org.apach...

     

    项目环境:

    jdk1.8+spring4.3.12

    一、问题描述及试用场景:

    在项目开发中,经常用调用http接口,下面是封装apache的httpclient工具类。

    二、样例代码:

     

     

    package org.egg.utils;
    
    import org.apache.http.client.config.RequestConfig;
    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.impl.conn.PoolingHttpClientConnectionManager;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.nio.charset.Charset;
    
    /**
     * @author dataochen
     * @Description
     * @date: 2017/11/7 17:49
     */
    public class HttpRequestUtil {
        private static CloseableHttpClient httpClient;
    
        static {
            PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
            cm.setMaxTotal(100);
            cm.setDefaultMaxPerRoute(20);
            cm.setDefaultMaxPerRoute(50);
            httpClient = HttpClients.custom().setConnectionManager(cm).build();
        }
    
        public static String get(String url) {
            CloseableHttpResponse response = null;
            BufferedReader in = null;
            String result = "";
            try {
                HttpGet httpGet = new HttpGet(url);
                RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
                httpGet.setConfig(requestConfig);
                httpGet.setConfig(requestConfig);
                httpGet.addHeader("Content-type", "application/json; charset=utf-8");
                httpGet.setHeader("Accept", "application/json");
                response = httpClient.execute(httpGet);
                in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                StringBuffer sb = new StringBuffer("");
                String line = "";
                String NL = System.getProperty("line.separator");
                while ((line = in.readLine()) != null) {
                    sb.append(line + NL);
                }
                in.close();
                result = sb.toString();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (null != response) {
                        response.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return result;
        }
    
        public static String post(String url, String jsonString) {
            CloseableHttpResponse response = null;
            BufferedReader in = null;
            String result = "";
            try {
                HttpPost httpPost = new HttpPost(url);
                RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
                httpPost.setConfig(requestConfig);
                httpPost.setConfig(requestConfig);
                httpPost.addHeader("Content-type", "application/json; charset=utf-8");
                httpPost.setHeader("Accept", "application/json");
                httpPost.setEntity(new StringEntity(jsonString, Charset.forName("UTF-8")));
                response = httpClient.execute(httpPost);
                in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                StringBuffer sb = new StringBuffer("");
                String line = "";
                String NL = System.getProperty("line.separator");
                while ((line = in.readLine()) != null) {
                    sb.append(line + NL);
                }
                in.close();
                result = sb.toString();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (null != response) {
                        response.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return result;
        }
    
    }
    

     

     

     

     

    代码所用jar包maven坐标:

    <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.3</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpcore</artifactId>
        <version>4.4.8</version>
    </dependency>

     

     

     

    外链推广:分享一好玩有趣小程序----欢乐鲸工具箱,集摇色子,免费小说,手持弹幕,微信九宫格切图,备忘录,语音随心录,计算器,程序员老黄历,尺子等于一身的便民小程序。永久免费使用。

     

    项目地址:https://github.com/SuperEggMan/renting_frame_finish_bek; ps:感兴趣的可以start哦!

    声明:此项目仅是抛砖引玉,内容不是特别完善。如有转载,请注明此处。

     

    展开全文
  • http请求工具类

    2019-04-13 11:38:25
    简单的http请求,短连接,请求完成之后就结束了,后期增加长连接请求. import org.apache.commons.codec.digest.DigestUtils; import org.apache.http.*; import org.apache.http.client.HttpClient; import org....

    简单的http请求,短连接,请求完成之后就结束了,

    
    import org.apache.commons.codec.digest.DigestUtils;
    import org.apache.http.*;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.client.methods.HttpUriRequest;
    import org.apache.http.client.methods.RequestBuilder;
    import org.apache.http.entity.ContentType;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.entity.mime.FormBodyPart;
    import org.apache.http.entity.mime.MultipartEntity;
    import org.apache.http.entity.mime.content.StringBody;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.protocol.HTTP;
    import org.apache.http.util.EntityUtils;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.net.HttpURLConnection;
    import java.net.URI;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.nio.charset.Charset;
    import java.util.*;
    import java.util.Map.Entry;
    
    /**
     * @author rdd 2018.03.13
     */
    public class HttpUtils {
    
        public static final String charset = "utf-8";
    
        public static final int JS_TIME_OUT = 6000;
    
        /**
         * 不带参数的post请求,用的很少
         *
         * @param myURL
         * @return
         */
        public static String doPostUrl(String myURL) {
            URL url;
            try {
                url = new URL(myURL);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(JS_TIME_OUT);
                conn.setReadTimeout(JS_TIME_OUT);
                conn.setRequestMethod("POST");// 提交模式
                // 是否允许输入输出
                conn.setDoInput(true);
                conn.setDoOutput(true);
                // 设置请求头里面的数据,以下设置用于解决http请求code415的问题
                conn.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
                // 链接地址
                conn.connect();
                OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
                // 发送参数
                // 清理当前编辑器的左右缓冲区,并使缓冲区数据写入基础流
                writer.flush();
                int code = conn.getResponseCode();
                BufferedReader reader = null;
                if (code == 200) {
    //                is = conn.getInputStream(); // 得到网络返回的输入流
                    reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                } else {
    //                is = conn.getErrorStream(); // 得到网络返回的输入流
                    reader = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
                }
    //            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                String lines = reader.readLine();
                reader.close();
                return lines;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    
        private static String getSortURL(TreeMap<String, Object> mp, String head) {
            try {
                String url = "";
                Iterator<String> it = mp.keySet().iterator();
                StringBuffer sb = new StringBuffer();
                while (it.hasNext()) {
                    Object key = it.next();
                    url = url + key + "=" + URLEncoder.encode(mp.get(key).toString(), charset) + "&";
                    sb.append("|").append(mp.get(key));
                }
                return head + "?" + url;
            } catch (Exception e) {
                e.printStackTrace();
                return "";
            }
        }
    
        private static String postForm(String reqURL, TreeMap<String, Object> params) {
            CloseableHttpClient httpclient = HttpClients.custom().build();
            try {
                RequestBuilder builder = RequestBuilder.post(reqURL);
                builder.setCharset(Charset.forName(charset));
                MultipartEntity httpEntity = new MultipartEntity();
                if (params != null) {
                    for (Entry<String, Object> entry : params.entrySet()) {
                        FormBodyPart formBodyPart = new FormBodyPart(entry.getKey(),
                                new StringBody(String.valueOf(entry.getValue()), "text/plain", Charset.forName(charset)));
                        httpEntity.addPart(formBodyPart);
                    }
                }
                builder.setEntity(httpEntity);
                HttpUriRequest post = builder.build();
                CloseableHttpResponse response = httpclient.execute(post);
                try {
                    HttpEntity entity = response.getEntity();
                    Charset respCharset = ContentType.getOrDefault(entity).withCharset(charset).getCharset();
                    String result = EntityUtils.toString(entity, respCharset);
                    EntityUtils.consume(entity);
                    return result;
                } finally {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    httpclient.close();
                } catch (IOException e) {
                }
            }
            return null;
        }
    
        private static String getMD5(String str) {
            try {
                return DigestUtils.md5Hex(str);
            } catch (Exception e) {
                throw new RuntimeException("MD5加密出现错误");
            }
        }
    
    
        /**
         * post请求(用于key-value格式的参数)
         *
         * @param url
         * @param params
         * @return
         */
        public static String doPost(String url, Map params) {
            BufferedReader in = null;
            try {
                // 定义HttpClient
                HttpClient client = new DefaultHttpClient();
                // 实例化HTTP方法
                HttpPost request = new HttpPost();
                request.setURI(new URI(url));
                //设置参数
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                for (Iterator iter = params.keySet().iterator(); iter.hasNext(); ) {
                    String name = (String) iter.next();
                    String value = String.valueOf(params.get(name));
                    nvps.add(new BasicNameValuePair(name, value));
    
                    //System.out.println(name +"-"+value);
                }
                request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
    
                HttpResponse response = client.execute(request);
                int code = response.getStatusLine().getStatusCode();
                if (code == 200) {    //请求成功
                    in = new BufferedReader(new InputStreamReader(response.getEntity()
                            .getContent(), "utf-8"));
                    StringBuffer sb = new StringBuffer("");
                    String line = "";
                    String NL = System.getProperty("line.separator");
                    while ((line = in.readLine()) != null) {
                        sb.append(line + NL);
                    }
    
                    in.close();
    
                    return sb.toString();
                } else {    //
                    System.out.println("状态码:" + code);
                    return null;
                }
            } catch (Exception e) {
                e.printStackTrace();
    
                return null;
            }
        }
    
        /**
         * post请求(用于请求json格式的参数)
         *
         * @param url
         * @param params
         * @return
         */
        public static String doPost(String url, String params) throws Exception {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);// 创建httpPost
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-Type", "application/json");
            String charSet = "UTF-8";
            StringEntity entity = new StringEntity(params, charSet);
            httpPost.setEntity(entity);
            CloseableHttpResponse response = null;
            try {
                response = httpclient.execute(httpPost);
                StatusLine status = response.getStatusLine();
                int state = status.getStatusCode();
                if (state == HttpStatus.SC_OK) {
                    HttpEntity responseEntity = response.getEntity();
                    String jsonString = EntityUtils.toString(responseEntity);
                    return jsonString;
                } else {
    //                logger.error("请求返回:"+state+"("+url+")");
                }
            } finally {
                if (response != null) {
                    try {
                        response.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    
    }
    

    有时候请求使用长连接的话更加省资源,长连接请求.长连接工具类

    展开全文
  • http工具类

    2018-12-20 13:54:50
    提供一些常用的http方法 import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.http.NameValuePair; import org...
  • Http工具类 HttpUtils

    千次阅读 2019-05-09 17:08:51
    import java.io.IOException; import java.nio.charset.Charset; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.N....
  • http://www.captainbed.net/inner 我们知道,在spring项目中,只有都是容器中的bean才可以互取【依赖注入】,比如说userController和userService都是容器中的实例bean,所以在userController中可以注入userService...
  • 一、问题描述及试用场景: 在项目开发中,常常需要校验入参参数的合法性,是否...这里建议使用hibernate的工具包,稍加封装即可实现 三、样例源码: package org.egg.utils; import org.egg.enums.CommonErr
  • 静态工具类中使用注解注入service

    万次阅读 多人点赞 2014-07-15 16:43:25
    一般需要在一个工具类中使用@Autowired 注解注入一个service。但是由于工具类方法一般都写成static,所以直接注入就存在问题。 使用如下方式可以解决: /** * */ package cn.ffcs.drive.common.util; import ...
  • Spring中直接获取bean的工具类

    万次阅读 2011-04-27 16:11:00
    Spring中直接获取bean的工具类 此方法不需要将bean在配置文件中注入到使用类 1.建立listener,启动时加载配置
  • debug工具

    千次阅读 2017-03-16 12:02:49
    1、debug是什么 2、debug的使用
  • Android工具类库

    千次阅读 2017-04-06 09:38:59
    囊括了一大部分Android应用开发过程当中常用的工具类工具类来源整理自网络和自己编写。(正在不断收集和整理中) 快速使用: 在工程目录下的 build.gradle 添加如下代码:allprojects { repositories { ..
  • java读取XML文件通用工具类(递归调用) 源代码下载地址:http://www.zuidaima.com/share/1550463285480448.htm
  • 前言在开发spring web项目时,我们很多的Controller层代码都需要获取一下,HttpServletRequest、HttpServletResponse和HttpSession等对象,我们普遍的方式是在Controller下的方法参数中直接获取,例如:@Slf4j ...
  • 自动生成代码工具 通过freemarker模板生成MySQL数据库表对应的Javabean和mybatis mapper文件。... 工具类 数据库工具类 文件工具类 模板工具类 字符串工具类 配置文件工具类 bean类 其他类...
  • hutool工具类

    千次阅读 2017-11-13 16:58:36
    一个Java基础工具类,类似于jodd...一个Java基础工具类,对文件、流、加密解密、转码、正则、线程、XML等JDK方法进行封装,组成各种Util工具类,同时提供以下组件: 布隆过滤 缓存 克隆接口 类型转换
  • JAVA -----HTTP工具类

    万次阅读 2017-03-14 11:47:21
    package cn.zhangheng;import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL;...import java.net.URLConnection;...import
  • 【UML 建模】在线UML建模工具 ProcessOn 使用详解

    万次阅读 多人点赞 2015-08-17 22:33:22
    UML
  • Java 常用工具类整理

    千次阅读 2018-03-30 10:48:40
    一、org.apache.commons.io.IOUtils closeQuietly 关闭一个IO流、socket、或者selector且不抛出异常。通常放在finally块。 toString 转换IO流、 Uri、 byte[]为String。 copy IO流数据复制,从输入流写到输出...
1 2 3 4 5 ... 20
收藏数 958,632
精华内容 383,452
关键字:

http工具类