国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

HttpClient4.5 post請求xml到服務器

2019-11-08 01:52:03
字體:
來源:轉載
供稿:網友

1.加入HttpClient4.5和junit依賴包

<dependencies>		<dependency>			<groupId>org.apache.httpcomponents</groupId>			<artifactId>httpclient</artifactId>			<version>4.5</version>		</dependency>		<dependency>			<groupId>commons-collections</groupId>			<artifactId>commons-collections</artifactId>			<version>3.2.2</version>		</dependency>		<dependency>			<groupId>junit</groupId>			<artifactId>junit</artifactId>			<version>4.12</version>		</dependency>	</dependencies>

2.編寫工具類

import java.io.IOException;import java.security.cert.CertificateException;import java.security.cert.X509Certificate;import java.util.ArrayList;import java.util.List;import java.util.Map;import org.apache.commons.collections.MapUtils;import org.apache.http.Consts;import org.apache.http.HeaderIterator;import org.apache.http.HttpEntity;import org.apache.http.HttPResponse;import org.apache.http.HttpStatus;import org.apache.http.NameValuePair;import org.apache.http.ParseException;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.config.Registry;import org.apache.http.config.RegistryBuilder;import org.apache.http.conn.socket.ConnectionSocketFactory;import org.apache.http.conn.socket.PlainConnectionSocketFactory;import org.apache.http.conn.ssl.NoopHostnameVerifier;import org.apache.http.conn.ssl.SSLConnectionSocketFactory;import org.apache.http.conn.ssl.TrustStrategy;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;import org.apache.http.message.BasicNameValuePair;import org.apache.http.ssl.SSLContextBuilder;import org.apache.http.util.EntityUtils;/** *     * @ClassName: HttpsUtils    * @Description: TODO(https post忽略證書請求) */public class HttpsUtils {	private static final String HTTP = "http";	private static final String HTTPS = "https";	private static SSLConnectionSocketFactory sslsf = null;	private static PoolingHttpClientConnectionManager cm = null;	private static SSLContextBuilder builder = null;	static {		try {			builder = new SSLContextBuilder();			// 全部信任 不做身份鑒定			builder.loadTrustMaterial(null, new TrustStrategy() {				@Override				public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {					return true;				}			});			sslsf = new SSLConnectionSocketFactory(builder.build(),					new String[] { "SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2" }, null, NoopHostnameVerifier.INSTANCE);			Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create()					.register(HTTP, new PlainConnectionSocketFactory()).register(HTTPS, sslsf).build();			cm = new PoolingHttpClientConnectionManager(registry);			cm.setMaxTotal(200);// max connection		} catch (Exception e) {			e.printStackTrace();		}	}	/**	 * httpClient post請求	 * 	 * @param url	 *            請求url	 * @param header	 *            頭部信息	 * @param param	 *            請求參數 form提交適用	 * @param entity	 *            請求實體 json/xml提交適用	 * @return 可能為空 需要處理	 * @throws Exception	 *	 */	public static String post(String url, Map<String, String> header, Map<String, String> param, StringEntity entity)			throws Exception {		String result = "";		CloseableHttpClient httpClient = null;		try {			httpClient = getHttpClient();			//HttpGet httpPost = new HttpGet(url);//get請求			HttpPost httpPost = new HttpPost(url);//Post請求			// 設置頭信息			if (MapUtils.isNotEmpty(header)) {				for (Map.Entry<String, String> entry : header.entrySet()) {					httpPost.addHeader(entry.getKey(), entry.getValue());				}			}			// 設置請求參數			if (MapUtils.isNotEmpty(param)) {				List<NameValuePair> formparams = new ArrayList<NameValuePair>();				for (Map.Entry<String, String> entry : param.entrySet()) {					// 給參數賦值					formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));				}				UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);				httpPost.setEntity(urlEncodedFormEntity);			}			// 設置實體 優先級高			if (entity != null) {				httpPost.addHeader("Content-Type", "text/xml"); 				httpPost.setEntity(entity);			}			HttpResponse httpResponse = httpClient.execute(httpPost);			int statusCode = httpResponse.getStatusLine().getStatusCode();			System.out.println("狀態碼:"+statusCode);			if (statusCode == HttpStatus.SC_OK) {				HttpEntity resEntity = httpResponse.getEntity();				result = EntityUtils.toString(resEntity);			} else {				readHttpResponse(httpResponse);			}		} catch (Exception e) {			throw e;		} finally {			if (httpClient != null) {				httpClient.close();			}		}		return result;	}
	
/**	 * httpClient post請求	 * 	 * @param url	 *            請求url	 * @param header	 *            頭部信息	 * @param param	 *            請求參數 form提交適用	 * @param entity	 *            請求實體 json/xml提交適用 (指定參數名的方式來POST數據)	 * @return 可能為空 需要處理	 * @throws Exception	 *	 */	public static String post(String url, Map<String, String> header, Map<String, String> param, HttpEntity entity)			throws Exception {		String result = "";		CloseableHttpClient httpClient = null;		try {			httpClient = getHttpClient();			//HttpGet httpPost = new HttpGet(url);//get請求			HttpPost httpPost = new HttpPost(url);//Post請求			// 設置頭信息			if (MapUtils.isNotEmpty(header)) {				for (Map.Entry<String, String> entry : header.entrySet()) {					httpPost.addHeader(entry.getKey(), entry.getValue());				}			}			// 設置請求參數			if (MapUtils.isNotEmpty(param)) {				List<NameValuePair> formparams = new ArrayList<NameValuePair>();				for (Map.Entry<String, String> entry : param.entrySet()) {					// 給參數賦值					formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));				}				UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);				httpPost.setEntity(urlEncodedFormEntity);			}			// 設置實體 優先級高			if (entity != null) {				httpPost.setEntity(entity);			}			HttpResponse httpResponse = httpClient.execute(httpPost);			int statusCode = httpResponse.getStatusLine().getStatusCode();			System.out.println("狀態碼:"+statusCode);			if (statusCode == HttpStatus.SC_OK) {				HttpEntity resEntity = httpResponse.getEntity();				result = EntityUtils.toString(resEntity);			} else {				readHttpResponse(httpResponse);			}		} catch (Exception e) {			throw e;		} finally {			if (httpClient != null) {				httpClient.close();			}		}		return result;	}

	public static CloseableHttpClient getHttpClient() throws Exception {		CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).setConnectionManager(cm)				.setConnectionManagerShared(true).build();		return httpClient;	}	public static String readHttpResponse(HttpResponse httpResponse) throws ParseException, IOException {		StringBuilder builder = new StringBuilder();		// 獲取響應消息實體		HttpEntity entity = httpResponse.getEntity();		// 響應狀態		builder.append("status:" + httpResponse.getStatusLine());		builder.append("headers:");		HeaderIterator iterator = httpResponse.headerIterator();		while (iterator.hasNext()) {			builder.append("/t" + iterator.next());		}		// 判斷響應實體是否為空		if (entity != null) {			String responseString = EntityUtils.toString(entity);			builder.append("response length:" + responseString.length());			builder.append("response content:" + responseString.replace("/r/n", ""));		}		return builder.toString();	}}

3.測試類

@Test	public void testSendHttpPost2() {		String url = "https://XXXX.XXX.XXX.XXX/XXX/XXX.html";		try {			StringEntity entity = new StringEntity(getXMLString(), "UTF-8"); //不指定參數名的方式來POST數據			String responseContent = HttpsUtils.post(url, null, null, entity);			System.out.println(responseContent);		} catch (Exception e) {			e.printStackTrace();		}	}
@Test	public void testSendHttpPost3() {//https://209.160.54.4/suns/XML_Rx.php		String url = "http://10.122.1.92:8080/products.html";		try {			List<NameValuePair> formparams = new ArrayList<NameValuePair>(); 		    formparams.add(new BasicNameValuePair("xmldate", "<html>你好啊啊</html>")); //指定參數名的方式來POST數據		    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); 			String responseContent = HttpsUtils.post(url, null, null, entity);			System.out.println(responseContent);		} catch (Exception e) {			e.printStackTrace();		}	}


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 巴中市| 若尔盖县| 伊金霍洛旗| 玉树县| 临邑县| 湖口县| 南部县| 始兴县| 宁国市| 卢湾区| 延川县| 威海市| 环江| 周宁县| 股票| 衡东县| 聂荣县| 中西区| 玉门市| 元氏县| 丰镇市| 怀安县| 虹口区| 新平| 建水县| 潼关县| 思南县| 大悟县| 宁远县| 峨山| 武夷山市| 玛曲县| 乐昌市| 葵青区| 大名县| 棋牌| 新巴尔虎右旗| 河源市| 柳江县| 图们市| 井研县|