使用HttpClient,通常都須要設置鏈接超時時間和獲取數據超時時間。這兩個參數很重要,目的是爲了防止訪問其餘http服務時,因爲超時致使本身的應用受影響。java
4.5版本中,這兩個參數的設置都抽象到了RequestConfig中,由相應的Builder構建,具體的例子以下:apache
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 :設置鏈接超時時間,單位毫秒。ui
setConnectionRequestTimeout :設置從connect Manager獲取Connection 超時時間,單位毫秒。這個屬性是新加的屬性,由於目前版本是能夠共享鏈接池的。spa
setSocketTimeout :請求獲取數據的超時時間,單位毫秒。 若是訪問一個接口,多少時間內沒法返回數據,就直接放棄這次調用。code