http工具类

import java.net.Socket;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLEngine;
import javax.net.ssl.X509ExtendedTrustManager;

public class TrustAnyTrustManager extends X509ExtendedTrustManager {

	@Override
	public void checkClientTrusted(X509Certificate[] arg0, String arg1)
			throws CertificateException {

	}

	@Override
	public void checkServerTrusted(X509Certificate[] arg0, String arg1)
			throws CertificateException {

	}

	@Override
	public X509Certificate[] getAcceptedIssuers() {
		return new X509Certificate[0];
	}

	@Override
	public void checkClientTrusted(X509Certificate[] arg0, String arg1,
			Socket arg2) throws CertificateException {

	}

	@Override
	public void checkClientTrusted(X509Certificate[] arg0, String arg1,
			SSLEngine arg2) throws CertificateException {

	}

	@Override
	public void checkServerTrusted(X509Certificate[] arg0, String arg1,
			Socket arg2) throws CertificateException {

	}

	@Override
	public void checkServerTrusted(X509Certificate[] arg0, String arg1,
			SSLEngine arg2) throws CertificateException {

	}

}


import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.client.utils.HttpClientUtils;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

/**
 * http helper 暂时用closeablehttpclient,当有高并发需求时可考虑用http连接池管理
 * 1.http连接池不是万能的,过多的长连接会占用服务器资源,导致其他服务受阻 2.http连接池只适用于请求是经常访问同一主机(或同一个接口)的情况下
 * 3.并发数不高的情况下资源利用率低下
 */
public class HttpUtils {

	private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

	private static final int HTTP_CONNECT_TIME_OUT = 30 * 1000;

	private static final int HTTP_CRT_TIME_OUT = 1000;

	/**
	 * @param url
	 * @param context
	 * @return
	 */
	public static String post(String url, String context) {
		String responseJson = null;
		HttpResponse response = null;
		CloseableHttpClient httpclient = null;
		try {
			// 创建请求
			// httpclient = HttpClients.createDefault();
			httpclient = ignoreSSLClient();
			HttpPost post = new HttpPost(url);
			post.setHeader("Content-Type", "application/json;charset=UTF-8");
			StringEntity stringEntity = new StringEntity(context, CharSetConstants.DEFAULT_CHARSET_NAME);
			// stringEntity.setContentEncoding(CharSetConstants.DEFAULT_CHARSET_NAME);
			// stringEntity.setContentType("application/json");
			post.setEntity(stringEntity);
			// 设置超时 连接超时时间|从connect Manager(连接池)获取Connection
			// 超时时间|请求获取数据的超时时间(即响应时间)
			RequestConfig config = RequestConfig.custom().setConnectTimeout(HTTP_CONNECT_TIME_OUT)
					.setConnectionRequestTimeout(HTTP_CRT_TIME_OUT).setSocketTimeout(HTTP_CONNECT_TIME_OUT).build();
			post.setConfig(config);
			logger.info("http request url:{}", url);
			logger.debug("http request context:{}", CommonUtils.maskInfo(context));
			response = httpclient.execute(post);
			logger.info("http response statusCode:{}", response.getStatusLine().getStatusCode());
			if (200 == response.getStatusLine().getStatusCode()) {
				HttpEntity resEntity = response.getEntity();
				responseJson = EntityUtils.toString(resEntity);
				// 消耗掉response
				EntityUtils.consume(resEntity);
			}
		} catch (IOException e) {
			logger.error("http post occur IOException:", e);
		} catch (Exception e) {
			logger.error("http post occur Exception:", e);
		} finally {
			HttpClientUtils.closeQuietly(httpclient);
			HttpClientUtils.closeQuietly(response);
		}
		logger.info("http response: {}", CommonUtils.maskInfo(responseJson));
		return responseJson;
	}

	/**
	 * trust any manager
	 * 
	 * @return
	 * @throws Exception
	 */
	private static CloseableHttpClient ignoreSSLClient() throws Exception {
		SSLContext sslContext = SSLContext.getInstance("TLS");
		sslContext.init(null, new TrustManager[] {
			new TrustAnyTrustManager()
		}, null);
		// 创建httpClient
		CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext)
				.setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
		return client;
	}

	@SuppressWarnings("unchecked")
	public static String formPost(String url, String jsonStr) {
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;
		String resp = null;
		HttpPost post = new HttpPost(url);
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(HTTP_CONNECT_TIME_OUT)
				.setConnectionRequestTimeout(HTTP_CRT_TIME_OUT).setSocketTimeout(HTTP_CONNECT_TIME_OUT).build();
		post.setConfig(requestConfig);
		try {
			// httpclient = ignoreSSLClient();
			httpclient = HttpClients.createDefault();
			List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();
			Map<String, Object> map = JSONObject.parseObject(jsonStr, Map.class);
			Set<String> set = map.keySet();
			Iterator<String> it = set.iterator();
			while (it.hasNext()) {
				String jsonKey = it.next();
				formparams.add(new BasicNameValuePair(jsonKey, String.valueOf(map.get(jsonKey))));
			}
			post.setEntity(new UrlEncodedFormEntity(formparams, CharSetConstants.DEFAULT_CHARSET_NAME));
			logger.info("http request url:{}", url);
			logger.info("http request context:{}", CommonUtils.maskInfo(jsonStr));
			response = httpclient.execute(post);
			logger.info("http response statusCode:{}", response.getStatusLine().getStatusCode());
			resp = EntityUtils.toString(response.getEntity());
			logger.info("http response:{}", CommonUtils.maskInfo(resp));
		} catch (IOException e) {
			logger.error("http post occur IOException:", e);
		} catch (Exception e) {
			logger.error("http post occur Exception:", e);
		} finally {
			HttpClientUtils.closeQuietly(httpclient);
			HttpClientUtils.closeQuietly(response);
		}
		return resp;
	}

	public static String xmlPost(String url, String context) {
		String responseJson = null;
		HttpResponse response = null;
		CloseableHttpClient httpclient = null;
		try {
			// 创建请求
			// httpclient = HttpClients.createDefault();
			httpclient = ignoreSSLClient();
			HttpPost post = new HttpPost(url);
			post.setHeader("Content-Type", "application/xml;charset=UTF-8");
			StringEntity stringEntity = new StringEntity(context, CharSetConstants.DEFAULT_CHARSET_NAME);
			// stringEntity.setContentEncoding(CharSetConstants.DEFAULT_CHARSET_NAME);
			// stringEntity.setContentType("application/json");
			post.setEntity(stringEntity);
			// 设置超时 连接超时时间|从connect Manager(连接池)获取Connection
			// 超时时间|请求获取数据的超时时间(即响应时间)
			RequestConfig config = RequestConfig.custom().setConnectTimeout(HTTP_CONNECT_TIME_OUT)
					.setConnectionRequestTimeout(HTTP_CRT_TIME_OUT).setSocketTimeout(HTTP_CONNECT_TIME_OUT).build();
			post.setConfig(config);
			logger.info("http request url:{}", url);
			logger.info("http request context:{}", context);
			response = httpclient.execute(post);
			logger.info("http response statusCode:{}", response.getStatusLine().getStatusCode());
			if (200 == response.getStatusLine().getStatusCode()) {
				HttpEntity resEntity = response.getEntity();
				responseJson = EntityUtils.toString(resEntity);
				// 消耗掉response
				EntityUtils.consume(resEntity);
			}
		} catch (IOException e) {
			logger.error("http post occur IOException:", e);
		} catch (Exception e) {
			logger.error("http post occur Exception:", e);
		} finally {
			HttpClientUtils.closeQuietly(httpclient);
			HttpClientUtils.closeQuietly(response);
		}
		logger.info("http response: {}", responseJson);
		return responseJson;
	}

	public static void main(String[] args) {
		formPost("http://xxxxxxxx",
				"{\"jsonData\":\"张三\",\"checkValue\":\"asdafajsoghauohpisdnia\"}");
	}


	/**
	 * get
	 * 
	 * @param url
	 * @return
	 */
	public static String get(String url) {
		String responseJson = null;
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet get = new HttpGet(url);
		logger.info("http get url:{}", url);
		CloseableHttpResponse response = null;
		try {
			response = httpClient.execute(get);
			if (response != null && response.getStatusLine().getStatusCode() == 200) {
				HttpEntity resEntity = response.getEntity();
				responseJson = EntityUtils.toString(resEntity);
				// 消耗掉response
				EntityUtils.consume(resEntity);
			}
		} catch (IOException e) {
			logger.error("http get occur IOException:", e);
		} catch (Exception e) {
			logger.error("http get occur Exception:", e);
		} finally {
			HttpClientUtils.closeQuietly(httpClient);
			HttpClientUtils.closeQuietly(response);
		}
		logger.info("http get responseJson:{}", responseJson);
		return responseJson;
	}

	/**
	 * 
	 * @param fileUrl
	 * @param url
	 * @return
	 */
	public static String upload(String uploadFile, String uploadUrl, String jsonData, String checkValue) {
		logger.info("文件上传请求参数:uploadFile={},uploadUrl={},jsonData={},checkValue={}", uploadFile, uploadUrl, jsonData,
				checkValue);
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;
		InputStream ins = null;
		String result = null;
		File lcdFile = null;
		try {
			File file = new File(uploadFile);
			httpclient = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(uploadUrl);
			httpPost.setHeader("charset", "utf-8");
			MultipartEntityBuilder mEntityBuilder = MultipartEntityBuilder.create();
			if (file.exists()) {
				mEntityBuilder.addBinaryBody("picture", file);
			} else {
				URL url = new URL(uploadFile);
				ins = url.openStream();
				// mEntityBuilder.addBinaryBody("picture", stream);
				lcdFile = FileUtils.createTempFile("MER_PIC_" + System.currentTimeMillis(),
						uploadFile.substring(uploadFile.lastIndexOf(".")), ins);
				mEntityBuilder.addBinaryBody("picture", lcdFile);
			}
			ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
			mEntityBuilder.addTextBody("jsonData", jsonData, contentType);
			mEntityBuilder.addTextBody("checkValue", ShaUtil.encode(jsonData, "chinapnr", "UTF-8"), contentType);
			httpPost.setEntity(mEntityBuilder.build());
			response = httpclient.execute(httpPost);

			int statusCode = response.getStatusLine().getStatusCode();
			logger.info("文件上传 response statusCode:{}", response.getStatusLine().getStatusCode());
			if (statusCode == HttpStatus.SC_OK) {
				HttpEntity resEntity = response.getEntity();
				result = EntityUtils.toString(resEntity);
				logger.info("文件上传返回:{}", result);
				// 消耗掉response
				EntityUtils.consume(resEntity);
			}
		} catch (Exception e) {
			logger.error("文件上传异常:", e);
		} finally {
			if (ins != null) {
				try {
					ins.close();
				} catch (IOException e) {
					logger.error("关闭文件流句柄异常", e);
				}
				try {
					if (lcdFile != null) {
						lcdFile.delete();
					}
				} catch (Exception e) {
					logger.error("删除临时文件异常", e);
				}
			}
			HttpClientUtils.closeQuietly(httpclient);
			HttpClientUtils.closeQuietly(response);
		}
		return result;
	}

}
//File.java
public static File createTempFile(String prefix, String suffix, InputStream ins) {
		File temp = null;
		OutputStream os = null;
		try {
			File fileDir = new File(PyxisUtils.FILE_ROOT);
			if (!fileDir.exists()) {
				fileDir.mkdirs();
			}
			temp = File.createTempFile(prefix, suffix, fileDir);
			os = new FileOutputStream(temp);
			int bytesRead = 0;
			int length = 1024;
			byte[] buffer = new byte[length];
			while ((bytesRead = ins.read(buffer, 0, length)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
		} catch (IOException e) {
			logger.error("文件下载异常", e);
		} finally {
			try {
				if (os != null) {
					os.close();
				}
			} catch (IOException e) {
				logger.error("关闭文件流句柄失败", e);
			}
			try {
				if (ins != null) {
					ins.close();
				}
			} catch (IOException e) {
				logger.error("关闭文件流句柄失败", e);
			}
		}
		return temp;
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值