java实现httpclient

package org.gensis0.project.pcoms.service.utils;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
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.HttpPost;
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.fasterxml.jackson.databind.ObjectMapper;


public class HttpClientUtil {
	private static Logger log = LoggerFactory.getLogger(HttpClientUtil.class);


	public static Map<String, Object> httpPost(String url, Map<String, String> map) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		// HttpClient httpclient = new DefaultHttpClient();
		// HttpHost proxy = new HttpHost("10.47.24.20",30010, null);
		// httpclient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
		log.debug("报文内容:" + map);
		// 创建httppost
		HttpPost httppost = new HttpPost(url);
		HttpHost proxy = new HttpHost("10.47.24.20", 30010, "http");
		RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
		httppost.setConfig(config);
		// 创建参数队列
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		if (map != null && map.size() > 0) {
			for (String key : map.keySet()) {
				formparams.add(new BasicNameValuePair(key, map.get(key)));
			}
		}
		UrlEncodedFormEntity uefEntity;
		try {
			uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
			httppost.setEntity(uefEntity);
			log.debug("发送地址: " + httppost.getURI());
			CloseableHttpResponse response = httpclient.execute(httppost);
			// HttpResponse response = httpclient.execute(httppost);
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					String returnMsg = EntityUtils.toString(entity, "UTF-8");
					Map<String, Object> dMap = null;
					if(!(returnMsg.endsWith("}") && returnMsg.startsWith("{")))
					{
						dMap = new HashMap<String, Object>();
						dMap.put("returnMsg", returnMsg);
					}else {
						dMap = new ObjectMapper().readValue(returnMsg, Map.class);
					}


					// Map<String, Object> data = new HashMap<String, Object>();
					// data=(Map<String, Object>)dMap.get("data");
					// data.put("rep_status", dMap.get("status"));
					// data.put("rep_msg", dMap.get("msg"));
					// log.debug("--------------------------------------");
					// log.debug("返回报文:"+data);
					// log.debug("--------------------------------------");


					return dMap;
				}
			} catch (Exception e) {
				log.error("发送请求出错", e);
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			log.error("ClientProtocolException", e);
		} catch (UnsupportedEncodingException e1) {
			log.error("UnsupportedEncodingException", e1);
		} catch (IOException e) {
			log.error("IOException", e);
		} finally {
			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				log.error("finally IOException", e);
			}
		}
		return null;


	}


	/**
	 * 
	 * 发送HTTP请求
	 * 
	 * 
	 * 
	 * @param urlString
	 * 
	 * @return
	 * 
	 * @throws IOException
	 */


	public static String sendPost(String urlString, String method,
			Map<String, String> parameters, Map<String, String> propertys)


	{


		HttpURLConnection urlConnection = null;
		URL url;
		String response = "";
		try {
			url = new URL(urlString);
			urlConnection = (HttpURLConnection) url.openConnection();
			urlConnection.setRequestMethod(method);
			urlConnection.setDoOutput(true);
			urlConnection.setDoInput(true);
			urlConnection.setUseCaches(false);
			if (propertys != null)


				for (String key : propertys.keySet()) {


					urlConnection.addRequestProperty(key, propertys.get(key));


				}


			if (method.equalsIgnoreCase("POST") && parameters != null) {
				StringBuffer param = new StringBuffer();
				for (String key : parameters.keySet()) {
					param.append("&");
					param.append(key).append("=").append(parameters.get(key));


				}
				urlConnection.getOutputStream().write(param.toString().getBytes());
				urlConnection.getOutputStream().flush();


			}
			// 读取响应
			BufferedReader reader;
			reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
			String lines;


			while ((lines = reader.readLine()) != null) {
				lines = new String(lines.getBytes(), "utf-8");
				response += lines;
			}
			reader.close();
		} catch (MalformedURLException e) {
			log.error("MalformedURLException", e);
			e.printStackTrace();
		} catch (ProtocolException e) {
			log.error("ProtocolException", e);
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			log.error("UnsupportedEncodingException", e);
			e.printStackTrace();
		} catch (IOException e) {
			log.error("IOException", e);
			e.printStackTrace();
		}finally {
			// 断开连接
			urlConnection.disconnect();
		}
		return response;


	}


	// public static void main(String[] args) {
	// Map<String, String> map=new HashMap<String,String>();
	// map.put("f", "updateProjectStat");
	// map.put("foo", "a");
	// map.put("projectNo", "4");
	// map.put("status", "0002");
	//
	// Map<String, Object> map2=
	// HttpClientUtil.httpPost("http://d.ntclouds.cn:80/SHISIM_Service/a", map);
	// System.out.println(map2.get("status"));
	// }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值