使用HttpClient,一般都需要設置連接超時時間和獲取數據超時時間。這兩個參數很重要,目的是為了防止訪問其他http服務時,由於超時導致自己的應用受影響。
4.5版本中,這兩個參數的設置都抽象到了RequestConfig中,由相應的Builder構建,具體的例子如下:
1 import java.io.IOException; 2 3 import org.apache.http.Consts; 4 import org.apache.http.client.ClientProtocolException; 5 import org.apache.http.client.config.RequestConfig; 6 import org.apache.http.client.methods.CloseableHttpResponse; 7 import org.apache.http.client.methods.HttpGet; 8 import org.apache.http.impl.client.CloseableHttpClient; 9 import org.apache.http.impl.client.HttpClients; 10 import org.apache.http.util.EntityUtils; 11 12 /** 13 * @author 14 * 15 * @date 2017年5月18日 上午9:17:08 16 * 17 * @Description 18 */ 19 public class HttpGetUtils { 20 21 /** 22 * @param args 23 * @throws IOException 24 * @throws ClientProtocolException 25 */ 26 public static void main(String[] args) throws ClientProtocolException, IOException { 27 CloseableHttpClient httpclient = HttpClients.createDefault(); 28 HttpGet httpGet = new HttpGet("http://stackoverflow.com/"); 29 RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(1000) 30 .setSocketTimeout(5000).build(); 31 httpGet.setConfig(requestConfig); 32 CloseableHttpResponse response = httpclient.execute(httpGet); 33 System.out.println(response.getStatusLine());// 得到狀態行 34 System.out.println(EntityUtils.toString(response.getEntity(), Consts.UTF_8.name()));// 得到請求回來的數據 35 } 36 }
setConnectTimeout :設置連接超時時間,單位毫秒。
setConnectionRequestTimeout :設置從connect Manager獲取Connection 超時時間,單位毫秒。這個屬性是新加的屬性,因為目前版本是可以共享連接池的。
setSocketTimeout :請求獲取數據的超時時間,單位毫秒。 如果訪問一個接口,多少時間內無法返回數據,就直接放棄此次調用。