HttpClient入門示例

       如果你是使用maven來管理項目,你需要在pom.xml添加如下配置:

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.1</version>
        </dependency>

 

 

示例代碼如下:

package org.apache.http.examples.entity.mime;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.SSLException;

import org.apache.commons.codec.Charsets;
import org.apache.http.Header;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

/**
 * 使用HttpClient發送和接收Http請求
 * 
 * @author manzhizhen
 *
 */
public class HttpUtils {

	private static HttpClient httpClient;
	// 最大連接數
	private static final int MAX_CONNECTION = 100;
	// 每個route能使用的最大連接數,一般和MAX_CONNECTION取值一樣
	private static final int MAX_CONCURRENT_CONNECTIONS = 100;
	// 建立連接的超時時間,單位毫秒
	private static final int CONNECTION_TIME_OUT = 200;
	// 請求超時時間,單位毫秒
	private static final int REQUEST_TIME_OUT = 200;
	// 最大失敗重試次數
	private static final int MAX_FAIL_RETRY_COUNT = 3;
	// 請求配置,可以複用
	private static RequestConfig requestConfig;

	static {
		SocketConfig socketConfig = SocketConfig.custom()
				.setSoTimeout(REQUEST_TIME_OUT).setSoKeepAlive(true)
				.setTcpNoDelay(true).build();

		requestConfig = RequestConfig.custom()
				.setSocketTimeout(REQUEST_TIME_OUT)
				.setConnectTimeout(CONNECTION_TIME_OUT).build();
		/**
		 * 每個默認的 ClientConnectionPoolManager 實現將給每個route創建不超過2個併發連接,最多20個連接總數。
		 */
		PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
		connManager.setMaxTotal(MAX_CONNECTION);
		connManager.setDefaultMaxPerRoute(MAX_CONCURRENT_CONNECTIONS);
		connManager.setDefaultSocketConfig(socketConfig);

		httpClient = HttpClients.custom().setConnectionManager(connManager)
		// 添加重試處理器
				.setRetryHandler(new MyHttpRequestRetryHandler()).build();
	}

	public static void main(String[] args) {
		testGet();
	}

	/**
	 * 測試get方法
	 */
	private static void testGet() {
		String url = "http://restapi.amap.com/v3/place/text";
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("key", "95708f902ac2428ea119ec99fb70e6a3");
		paramMap.put("keywords", "互聯網金融大廈");
		paramMap.put("city", "330100");
		paramMap.put("extensions", "all");

		try {
			System.out.println(get(url, paramMap));

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * post請求
	 * 
	 * @param url
	 * @param paramMap
	 * @param headers
	 * @return
	 * @throws Exception
	 */
	public static String post(String url, Map<String, String> paramMap,
			List<Header> headers) throws Exception {
		URIBuilder uriBuilder = new URIBuilder(url);
		if (paramMap != null) {
			// 添加請求參數
			for (Entry<String, String> entry : paramMap.entrySet()) {
				uriBuilder.addParameter(entry.getKey(), entry.getValue());
			}
		}

		HttpPost httpPost = new HttpPost(uriBuilder.build());
		if (headers != null) {
			// 添加請求首部
			for (Header header : headers) {
				httpPost.addHeader(header);
			}
		}

		httpPost.setConfig(requestConfig);

		// 執行請求
		HttpResponse response = httpClient.execute(httpPost);

		return EntityUtils.toString(response.getEntity(), Charsets.UTF_8);
	}

	/**
	 * post請求,不帶請求首部
	 * 
	 * @param url
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	public static String post(String url, Map<String, String> paramMap)
			throws Exception {

		return post(url, paramMap, null);
	}

	/**
	 * get請求
	 * 
	 * @param url
	 * @param paramMap
	 * @param headers
	 * @return
	 * @throws Exception
	 */
	public static String get(String url, Map<String, String> paramMap,
			List<Header> headers) throws Exception {
		URIBuilder uriBuilder = new URIBuilder(url);
		if (paramMap != null) {
			// 添加請求參數
			for (Entry<String, String> entry : paramMap.entrySet()) {
				uriBuilder.addParameter(entry.getKey(), entry.getValue());
			}
		}

		HttpGet httpGet = new HttpGet(uriBuilder.build());
		if (headers != null) {
			// 添加請求首部
			for (Header header : headers) {
				httpGet.addHeader(header);
			}
		}

		httpGet.setConfig(requestConfig);

		// 執行請求
		HttpResponse response = httpClient.execute(httpGet);

		return EntityUtils.toString(response.getEntity(), Charsets.UTF_8);
	}

	/**
	 * get請求,不帶請求首部
	 * 
	 * @param url
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	public static String get(String url, Map<String, String> paramMap)
			throws Exception {

		return get(url, paramMap, null);
	}

	/**
	 * 請求重試處理器
	 * @author manzhizhen
	 *
	 */
	private static class MyHttpRequestRetryHandler implements
			HttpRequestRetryHandler {

		@Override
		public boolean retryRequest(IOException exception, int executionCount,
				HttpContext context) {
			if (executionCount >= MAX_FAIL_RETRY_COUNT) {
				return false;
			}

			if (exception instanceof InterruptedIOException) {
				// 超時
				return false;
			}
			if (exception instanceof UnknownHostException) {
				// 未知主機
				return false;
			}
			if (exception instanceof ConnectTimeoutException) {
				// 連接被拒絕
				return false;
			}
			if (exception instanceof SSLException) {
				// SSL handshake exception
				return false;
			}

			HttpClientContext clientContext = HttpClientContext.adapt(context);
			HttpRequest request = clientContext.getRequest();
			boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
			if (idempotent) {
				// 如果請求被認爲是冪等的,則重試
				return true;
			}

			return false;
		}
	}
}

 

發佈了48 篇原創文章 · 獲贊 49 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章