專案一(一) HttpClient中的POST請求和GET請求

u013457570發表於2017-03-16

HttpClient中的POST請求和GET請求

一、HttpClient簡述

HttpClient是Apache Jakarta Common下的子專案,用來提供高效的、最新的、功能豐富的支援HTTP協議的客戶端程式設計工具包,並且它支援HTTP協議最新的版本和建議。HttpClient已經應用在很多的專案中,比如Apache Jakarta上很著名的另外兩個開源專案Cactus和HTMLUnit都使用了HttpClient。

          裡面封裝所有的請qui引數和相關資訊。

二、請求步驟

     HttpClient請求主要分為四大步驟即可完成

1、第一步:建立HttpClient物件
2、步驟二:建立請求的方法,指定url
3、步驟三:對請求引數進行編碼、設定。
4、步驟四:進行通訊並對返回的報文做處理

三、首先使用HttpClient必須已用相對應的包,在以下的案例中引用到了三個jar包

httpclient-4.3.3.jar
httpcore-4.3.2.jar
log4j-1.2.16.jar
commons-logging-1.0.4.jar

四、程式碼案例

package com.flx.dome1;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Date;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
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.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
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.util.EntityUtils;


/**
 * 
 * @author FuLX
 *
 */
public class HttpTool {

	/**
	 * 用https方式發出post請求
	 * 
	 * @param url
	 * @param entity
	 *            要傳送的字串
	 * @return
	 */
	public static String httpPost(String url, String entity) {
		if (url == null || url.length() == 0) {
			return null;
		}

		//1、第一步:建立HttpClient物件
		HttpClient httpClient = createSSLClientDefault();
		//2、步驟二:建立請求的方法,指定url
		HttpPost httpPost = new HttpPost(url);
		httpPost.setHeader("Connection", "Close");
		Date date1 = new Date();
		System.out.println("url==" + url);
		System.out.println("request==" + entity);
		try {
			//3、步驟三:對請求引數進行編碼、設定。
			httpPost.setEntity(new StringEntity(new String(entity
					.getBytes("UTF-8"), "ISO8859-1")));
			httpPost.setHeader("Accept", "application/xml");
			httpPost.setHeader("Content-type", "application/xml");
            //4、步驟四:進行通訊並對返回的報文做處理
			HttpResponse resp = httpClient.execute(httpPost);
			if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
				return null;
			}
			String res = EntityUtils.toString(resp.getEntity(), "UTF-8");

			// if (log.isDebugEnabled()) {
			Date date2 = new Date();
			long l = date2.getTime() - date1.getTime();
			System.out.println("time==" + l);
			if (l > 10000) {
				System.out.println("超過10秒==" + l);
			}
			System.out.println("response==" + res);
			// }
			return res;
		} catch (Exception e) {
			System.out.println("url==" + url);
			System.out.println("request==" + entity);
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	/**
	 * 用https方式發出get請求
	 * 
	 * @param url
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static String sendRequest(String url) throws IOException,
			ClientProtocolException {
		CloseableHttpClient httpclient = createSSLClientDefault();
		HttpGet httpget = new HttpGet(url);
		// httpget.setHeader("Connection", "Close");
		// System.out.println("executing request" + httpget.getRequestLine());
		CloseableHttpResponse response = httpclient.execute(httpget);
		try {
			HttpEntity entity = response.getEntity();

			// System.out.println("----------------------------------------");
			// System.out.println(response.getStatusLine());

			if (entity != null) {
				// System.out.println("Response content length: "
				// + entity.getContentLength());
			}
			String responseStr = EntityUtils.toString(entity, "UTF-8");
			return responseStr;
		} finally {
			response.close();
		}
	}

	public static CloseableHttpClient createSSLClientDefault() {
		try {
			SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(
					null, new TrustStrategy() {
						// 信任所有
						public boolean isTrusted(X509Certificate[] chain,
								String authType) throws CertificateException {
							return true;
						}
					}).build();
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
					sslContext);
			return HttpClients.custom().setSSLSocketFactory(sslsf).build();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (KeyStoreException e) {
			e.printStackTrace();
		}
		return HttpClients.createDefault();
	}
	
	public final static void main(String[] args) throws Exception {
		String url="http://localhost:8080/SSO/access/joinup?requestSource=wapPay2&userCode=99C1C32FAA23027414AEF464A7AFEF0A41AE1FE7965E947D6CBAF4BED0495FA7&clientName=H007001&target=cx";
		String requestStr="<request><cityMsg><cityCarNo>000000</cityCarNo><city>上海市</city></cityMsg><vehicle><ownerName>張三</ownerName><registerDate>1</registerDate><frameNo>2</frameNo><engineNo>3</engineNo><licInput>滬ATEST</licInput></vehicle></request>";
        //post請求		
		String respsonsePost = HttpTool.httpPost(url, requestStr);
		//get請求	
		String respsonseGet = HttpTool.sendRequest(url);
		System.out.println("POST返回引數:" + respsonsePost);
		System.out.println("GET返回引數:" + respsonseGet);
	}

}

五、結果展示

POST返回引數:<response><head><status>S</status></head><body><url>http://b.test.com:8080/cxInterface/goSinopecJoin.do?ticket=56594999-7667-41b8-ad01-2bc9446349421489655631439</url></body></response>
GET返回引數:<response><head><status>S</status></head><body><url>http://b.test.com:8080/cxInterface/goSinopecJoin.do?ticket=d9a418f3-2cfd-4ce8-9a0f-2a14d5e09e0d1489655631517</url></body></response>


相關文章