java http proxy request demo

package com.ygsoft.community.regulation.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
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.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;

public class HttpUtil {

	public static void main(String args[]) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		map.put("flag", "0");
		map.put("TypeID", "root_gr_ztfl_hj");
		map.put("pageNo", "1");
		map.put("pageSize", "100");
		new HttpUtil().post(map, "http://wsbs.jinwan.gov.cn/wsbs/f/matterList");
	}

	private String proxyHost;

	private int proxyPort;

	public HttpUtil() {
		this.proxyHost = "10.1.5.78";
		this.proxyPort = 3128;
	}

	public HttpUtil(String proxyHost, Integer proxyPort) {
		this.proxyHost = proxyHost;
		this.proxyPort = proxyPort;
	}

	@SuppressWarnings("rawtypes")
	public String post(Map buzReqParams, String reqUrl) throws Exception {
		String result = null;
		// 创建HttpClientBuilder
		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
		// HttpClient
		CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
		// 依次是目标请求地址,端口号,协议类型
		HttpHost target = new HttpHost(reqUrl, 80, "http");
		// 依次是代理地址,代理端口号,协议类型
		HttpHost proxy = new HttpHost(this.proxyHost, this.proxyPort, "http");
		RequestConfig config = RequestConfig.custom().setProxy(proxy).build();

		// 请求地址
		HttpPost httpPost = new HttpPost(reqUrl);
		httpPost.setConfig(config);
		// 创建参数队列
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		Set set = buzReqParams.keySet();
		Iterator it = set.iterator();
		while (it.hasNext()) {
			String key = (String) it.next();
			formparams.add(new BasicNameValuePair(key, (String) buzReqParams
					.get(key)));
		}
		UrlEncodedFormEntity entity;
		try {
			entity = new UrlEncodedFormEntity(formparams, "UTF-8");
			httpPost.setEntity(entity);
			CloseableHttpResponse response = closeableHttpClient.execute(
					target, httpPost);
			HttpEntity httpEntity = response.getEntity();
			if (httpEntity != null) {
				result = EntityUtils.toString(httpEntity, "UTF-8");
				// 打印响应内容
				System.out.println("response:" + result);
			}
			// 释放资源
			closeableHttpClient.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}

猜你喜欢

转载自jadeluo.iteye.com/blog/2380888