溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

HttpClient的使用實例

發(fā)布時間:2021-08-19 10:00:16 來源:億速云 閱讀:208 作者:chen 欄目:云計算

本篇內容主要講解“HttpClient的使用實例”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“HttpClient的使用實例”吧!

HttpClient的使用:

1)httpClient的簡單使用:

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
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;

public class HttpClientDemo {

	public static void main(String[] args) throws Exception {

		// 1.創(chuàng)建Httpclient對象
		CloseableHttpClient httpclient = HttpClients.createDefault();

		// 2.1創(chuàng)建http GET請求,并設置參數(shù)
		String url = "http://www.jxn.com/";
		URI uri = new URIBuilder(url).setParameter("name", "jack").setParameter("age", "1").build();
		HttpGet httpGet = new HttpGet(uri);

		// 2.2創(chuàng)建http POST請求,并設置參數(shù)
		HttpPost httpPost = new HttpPost(url);
		List<NameValuePair> parameters = new ArrayList<NameValuePair>();
		parameters.add(new BasicNameValuePair("name", "jack"));
		parameters.add(new BasicNameValuePair("age", "1"));
		UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
		httpPost.setEntity(formEntity);
				
		// 3.構建請求配置信息
		RequestConfig config = RequestConfig.custom().setConnectTimeout(1000) // 創(chuàng)建連接的最長時間
				.setConnectionRequestTimeout(500) // 從連接池中獲取到連接的最長時間
				.setSocketTimeout(10 * 1000) // 數(shù)據(jù)傳輸?shù)淖铋L時間
				.setStaleConnectionCheckEnabled(true) // 提交請求前測試連接是否可用
				.build();
		httpGet.setConfig(config);
		httpPost.setConfig(config);

		CloseableHttpResponse response = null;
		try {
			// 4.執(zhí)行請求
			response = httpclient.execute(httpGet);
//            response = httpclient.execute(httpPost);
						
			if (response.getStatusLine().getStatusCode() == 200) { // 判斷返回狀態(tài)是否為200
				String content = EntityUtils.toString(response.getEntity(), "UTF-8");
				System.out.println(content);
			}	
		} finally {
			if (response != null) {
				response.close();
			}
			httpclient.close();
		}
	}
}

2)使用httpClient連接池:

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.HttpClientConnectionManager;
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.util.EntityUtils;

public class HttpClientConnectionManagerDemo {

	public static void main(String[] args) throws Exception {
		PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
		connectionManager.setMaxTotal(200); 			// 設置最大連接數(shù)
		connectionManager.setDefaultMaxPerRoute(20); 	// 設置每個主機地址的并發(fā)數(shù)

		// 執(zhí)行一次get請求
		doGet(connectionManager);
	}

	public static void doGet(HttpClientConnectionManager connectionManager) throws Exception {
		CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();

		String url = "http://www.jxn.com/";
		HttpGet httpGet = new HttpGet(url);

		CloseableHttpResponse response = null;
		try {
			response = httpClient.execute(httpGet);
			if (response.getStatusLine().getStatusCode() == 200) {
				String content = EntityUtils.toString(response.getEntity(), "UTF-8");
				System.out.println(content);
			}
		} finally {
			if (response != null) {
				response.close();
			}
			// 此處不能關閉httpClient!如果把httpClient關閉掉,則連接池也會被銷毀
			// httpClient.close();
		}
	}
}

3)HttpClient與Spring整合:

【1】pom.xml文件:

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.3.5</version>
</dependency>

【2】spirng配置文件applicationContext-httpclient.xml:

<!-- 定義httpClient連接管理器 -->
<bean id="httpClientConnectionManager"
	class="org.apache.http.impl.conn.PoolingHttpClientConnectionManager">
	<property name="maxTotal" value="${http.maxTotal}" />
	<property name="defaultMaxPerRoute" value="${http.defaultMaxPerRoute}" />
</bean>

<!-- httpclient的構建器 -->
<bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder">
	<property name="connectionManager" ref="httpClientConnectionManager" />
</bean>

<!-- 定義Httpclient對象。注意:該對象是多例的! -->
<bean class="org.apache.http.impl.client.CloseableHttpClient"
	factory-bean="httpClientBuilder" factory-method="build" scope="prototype">
</bean>

<!-- 請求參數(shù)的構建器 -->
<bean id="requestConfigBuilder" class="org.apache.http.client.config.RequestConfig.Builder">
	<!-- 創(chuàng)建連接的最長時間 -->
	<property name="connectTimeout" value="${http.connectTimeout}" />
	<!-- 從連接池中獲取到連接的最長時間 -->
	<property name="connectionRequestTimeout" value="${http.connectionRequestTimeout}" />
	<!-- 數(shù)據(jù)傳輸?shù)淖铋L時間 -->
	<property name="socketTimeout" value="${http.socketTimeout}" />
	<!-- 提交請求前測試連接是否可用 -->
	<property name="staleConnectionCheckEnabled" value="${http.staleConnectionCheckEnabled}" />
</bean>

<!-- 定義請求參數(shù)對象 -->
<bean class="org.apache.http.client.config.RequestConfig" factory-bean="requestConfigBuilder" factory-method="build" />

<!-- 定期關閉無效的連接 -->
<bean class="com.jxn.common.httpclient.IdleConnectionEvictor">
	<constructor-arg index="0" ref="httpClientConnectionManager" />
</bean>

屬性配置文件httpclient.properties:
	http.maxTotal=200
	http.defaultMaxPerRoute=50
	http.connectTimeout=1000
	http.connectionRequestTimeout=500
	http.socketTimeout=10000
	http.staleConnectionCheckEnabled=true

【3】封裝成Service:

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jxn.common.httpclient.HttpResult;

[@Service](https://my.oschina.net/service)
public class ApiService implements BeanFactoryAware {

	private BeanFactory beanFactory;

	@Autowired(required = false)
	private RequestConfig requestConfig;
	
	
	[@Override](https://my.oschina.net/u/1162528)
	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		this.beanFactory = beanFactory;
	}

	private CloseableHttpClient getHttpClient() {
		return this.beanFactory.getBean(CloseableHttpClient.class);
	}
	
	// 執(zhí)行GET請求
	public String doGet(String url) throws ClientProtocolException, IOException {

		HttpGet httpGet = new HttpGet(url);
		httpGet.setConfig(requestConfig);
		CloseableHttpResponse response = null;
		try {
			// 執(zhí)行請求
			response = getHttpClient().execute(httpGet);
			// 判斷返回狀態(tài)是否為200
			if (response.getStatusLine().getStatusCode() == 200) {
				return EntityUtils.toString(response.getEntity(), "UTF-8");
			}
		} finally {
			if (response != null) {
				response.close();
			}
		}
		return null;
	}

	// 帶有參數(shù)的GET請求
	public String doGet(String url, Map<String, String> params) throws ClientProtocolException, IOException,
			URISyntaxException {
		URIBuilder builder = new URIBuilder(url);
		for (Map.Entry<String, String> entry : params.entrySet()) {
			builder.setParameter(entry.getKey(), entry.getValue());
		}
		return doGet(builder.build().toString());
	}

	// 執(zhí)行post請求
	public HttpResult doPost(String url, Map<String, String> params) throws IOException {
		// 創(chuàng)建http POST請求
		HttpPost httpPost = new HttpPost(url);
		httpPost.setConfig(requestConfig);
		if (null != params) {
			List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
			for (Map.Entry<String, String> entry : params.entrySet()) {
				parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
			}
			// 構造一個form表單式的實體
			UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
			httpPost.setEntity(formEntity);
		}

		CloseableHttpResponse response = null;
		try {
			response = getHttpClient().execute(httpPost);
			return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(
					response.getEntity(), "UTF-8"));
		} finally {
			if (response != null) {
				response.close();
			}
		}
	}

	// 執(zhí)行post請求,發(fā)送json數(shù)據(jù)
	public HttpResult doPostJson(String url, String json) throws IOException {
		// 創(chuàng)建http POST請求
		HttpPost httpPost = new HttpPost(url);
		httpPost.setConfig(requestConfig);
		if (null != json) {
			// 構造一個字符串的實體
			StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
			httpPost.setEntity(stringEntity);
		}

		CloseableHttpResponse response = null;
		try {
			response = getHttpClient().execute(httpPost);
			return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(
					response.getEntity(), "UTF-8"));
		} finally {
			if (response != null) {
				response.close();
			}
		}
	}
}

// 返回的結果
public class HttpResult {

	private Integer code;
	private String data;

	public HttpResult() {
	}
	public HttpResult(Integer code, String data) {
		this.code = code;
		this.data = data;
	}
	public Integer getCode() {
		return code;
	}
	public void setCode(Integer code) {
		this.code = code;
	}
	public String getData() {
		return data;
	}
	public void setData(String data) {
		this.data = data;
	}
}

【4】實現(xiàn)定期關閉無效的連接:

import org.apache.http.conn.HttpClientConnectionManager;

public class IdleConnectionEvictor extends Thread {

	private final HttpClientConnectionManager connectionManager;

	private volatile boolean shutdown;

	// 創(chuàng)建IdleConnectionEvictor對象的時候,啟動線程
	public IdleConnectionEvictor(HttpClientConnectionManager connectionManager) {
		this.connectionManager = connectionManager;
		this.start();
	}

	[@Override](https://my.oschina.net/u/1162528)
	public void run() {
		try {
			while (!shutdown) {
				synchronized (this) {
					wait(5000);
					// 關閉失效的連接(每隔5秒檢查一次)
					connectionManager.closeExpiredConnections();
				}
			}
		} catch (InterruptedException ex) {
			// 結束
		}
	}

	public void shutdown() {
		shutdown = true;
		synchronized (this) {
			notifyAll();
		}
	}
}

到此,相信大家對“HttpClient的使用實例”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續(xù)學習!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI