技术成就梦想

代码如诗

原 HttpUtil 无知的小孩

2017年9月14日 未分类 0

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

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
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.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient; 
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpUtil {

	static String charset = "UTF-8";

	static Header[] headers = null;
	static CloseableHttpClient httpClient = null;
	static HttpClientContext context = null;
	static BasicCookieStore cookieStore = null;
	static RequestConfig requestConfig = null;

	private HttpUtil() {
	}

	static {
		init();
	}

	static void init() {
		context = HttpClientContext.create();
		cookieStore = new BasicCookieStore();
		requestConfig = RequestConfig.custom().build();
		httpClient = HttpClients.createDefault();
	}

	public static void addCookie(String name, String value, String domain,
			String path) {
		BasicClientCookie cookie = new BasicClientCookie(name, value);
		cookie.setDomain(domain);
		cookie.setPath(path);
		cookieStore.addCookie(cookie);
	}

	public static String get(String uri) throws UnsupportedEncodingException,
			ClientProtocolException, ParseException, URISyntaxException,
			IOException {
		HttpGet get = new HttpGet(uri);
		if (headers != null) {
			get.setHeaders(headers);
		}
		CloseableHttpResponse res = httpClient.execute(get);
		if (200 == res.getStatusLine().getStatusCode()) {
			return EntityUtils.toString(res.getEntity(), charset);
		} else {
			System.out.println("请求失败!" + res.getStatusLine().getStatusCode());
		}
		return "";
	}

	public static String get(String uri, Map<String, String> header)
			throws UnsupportedEncodingException, ClientProtocolException,
			ParseException, URISyntaxException, IOException {
		HttpGet get = new HttpGet(uri);
		if (headers != null) {
			get.setHeaders(headers);
		}
		for (String key : header.keySet()) {
			get.setHeader(key, header.get(key));
		}
		headers = get.getAllHeaders();
		CloseableHttpResponse res = httpClient.execute(get);
		if (200 == res.getStatusLine().getStatusCode()) {
			return EntityUtils.toString(res.getEntity(), charset);
		} else {
			System.out.println("请求失败!" + res.getStatusLine().getStatusCode());
		}
		return "";
	}

	public static String post(String uri, Map<String, String> header,
			Map<String, String> params) throws UnsupportedEncodingException,
			ClientProtocolException, ParseException, URISyntaxException,
			IOException {

		ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
		for (Map.Entry<String, String> param : params.entrySet()) {
			pairs.add(new BasicNameValuePair(param.getKey(), param.getValue()));
		}
		HttpPost post = new HttpPost(uri);
		if (headers != null) {
			post.setHeaders(headers);
		}
		for (String key : header.keySet()) {
			post.setHeader(key, header.get(key));
		}
		headers = post.getAllHeaders();
		CloseableHttpResponse res = httpClient.execute(post);
		if (200 == res.getStatusLine().getStatusCode()) {
			return EntityUtils.toString(res.getEntity(), charset);
		} else {
			System.out.println("请求失败!" + res.getStatusLine().getStatusCode());
		}
		return "";
	}

	public static String post(String uri, Map<String, String> params)
			throws UnsupportedEncodingException, ClientProtocolException,
			ParseException, URISyntaxException, IOException {

		ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
		for (Map.Entry<String, String> param : params.entrySet()) {
			pairs.add(new BasicNameValuePair(param.getKey(), param.getValue()));
		}
		HttpPost post = new HttpPost(uri);
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, charset);
		// 设置post求情参数
		post.setEntity(entity);
		if (headers != null) {
			post.setHeaders(headers);
		}
		CloseableHttpResponse res = httpClient.execute(post);
		if (200 == res.getStatusLine().getStatusCode()) {
			return EntityUtils.toString(res.getEntity(), charset);
		} else {
			System.out.println("请求失败!" + res.getStatusLine().getStatusCode());
		}
		return "";
	} 
}