HttpUtil.java 3.44 KB
package com.pashanhoo.common;

import com.google.common.collect.Lists;

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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class HttpUtil {

	public HttpUtil() {
	}


	public static String getReturnResByUrl(String url, Map<String, String> params,
										   Map<String, String> headers, String encode) throws IOException {
		Logger logger = LoggerFactory.getLogger(HttpUtil.class);
		CloseableHttpClient client = HttpClientBuilder.create().build();
		String res = "";
		HttpPost httppost = new HttpPost(url);
		if (encode == null) {
			encode = "utf-8";
		}
		Integer URLOUTTIME = 0;
		RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(URLOUTTIME)
				.setConnectTimeout(URLOUTTIME).setSocketTimeout(URLOUTTIME).build();
		httppost.setConfig(requestConfig);
		// 设置header
		if (headers != null && headers.size() > 0) {
			for (Map.Entry<String, String> entry : headers.entrySet()) {
				httppost.setHeader(entry.getKey(), entry.getValue());
			}
		}

		List<NameValuePair> urlParameters = Lists.newArrayList();
		if (params != null && params.size() > 0) {
			Iterator<String> it = params.keySet().iterator();
			while (it.hasNext()) {
				String key = it.next();
				urlParameters.add(new BasicNameValuePair(key, params.get(key)));
			}
			httppost.setEntity(new UrlEncodedFormEntity(urlParameters, encode));
		}


		CloseableHttpResponse response = client.execute(httppost);
		if (response.getStatusLine().getStatusCode() == 200) {
			res = EntityUtils.toString(response.getEntity(), encode);
		}
		logger.info("http post back:" + res);
		httppost.releaseConnection();
		response.close();
		client.close();
		return res;

	}


	public static String get(String url, List<NameValuePair> params, Map<String, String> headers)
	{
		String body = null;
		try
		{
			HttpGet httpget = new HttpGet(url);

			String str = EntityUtils.toString(new UrlEncodedFormEntity(params, "UTF-8"));
			String f = url.indexOf("?") > -1 ? "&" : "?";
			httpget.setURI(new URI(httpget.getURI().toString() + f + str));

			CloseableHttpClient hc = HttpClientBuilder.create().build();
			if ((headers != null) && (headers.size() > 0)) {
				for (Map.Entry entry : headers.entrySet()) {
					httpget.setHeader((String)entry.getKey(), (String)entry.getValue());
				}
			}
			Object httpresponse = hc.execute(httpget);
			if (((HttpResponse)httpresponse).getStatusLine().getStatusCode() == 200)
			{
				HttpEntity entity = ((HttpResponse)httpresponse).getEntity();
				body = EntityUtils.toString(entity);
				if (entity != null)
					entity.consumeContent();
			}
			else
			{
				httpget.abort();
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return body;
	}
}