当前位置: 首页 >服务端 > java实现httpclient

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 retuMsg = EntityUtils.toString(entity, "UTF-8");					Map<String, Object> dMap = null;					if(!(retuMsg.endsWith("}") && retuMsg.startsWith("{")))					{						dMap = new HashMap<String, Object>();						dMap.put("retuMsg", retuMsg);					}else {						dMap = new ObjectMapper().readValue(retuMsg, 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("--------------------------------------");					retu 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);			}		}		retu null;	}	/**	 * 	 * 发送HTTP请求	 * 	 * 	 * 	 * @param urlString	 * 	 * @retu	 * 	 * @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();		}		retu 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"));	// }}

作者:孤独冷
来源链接:https://blog.csdn.net/zqw958252871/article/details/80004880

版权声明:
1、JavaClub(https://www.javaclub.cn)以学习交流为目的,由作者投稿、网友推荐和小编整理收藏优秀的IT技术及相关内容,包括但不限于文字、图片、音频、视频、软件、程序等,其均来自互联网,本站不享有版权,版权归原作者所有。

2、本站提供的内容仅用于个人学习、研究或欣赏,以及其他非商业性或非盈利性用途,但同时应遵守著作权法及其他相关法律的规定,不得侵犯相关权利人及本网站的合法权利。
3、本网站内容原作者如不愿意在本网站刊登内容,请及时通知本站(javaclubcn@163.com),我们将第一时间核实后及时予以删除。





本文链接:https://www.javaclub.cn/server/112113.html

标签:HttpClient
分享给朋友: