鍍金池/ 問(wèn)答/Java  網(wǎng)絡(luò)安全/ httpPost設(shè)置連接超時(shí)

httpPost設(shè)置連接超時(shí)

clipboard.png
這個(gè)要怎么設(shè)置連接超時(shí),不是響應(yīng)超時(shí),HttpMethodParams.SO_TIMEOUT我看網(wǎng)上寫(xiě)的這個(gè)代表請(qǐng)求超時(shí),求指教

引用文字
回答
編輯回答
墨沫

你是用的HttpClient版本是多少?不通版本下設(shè)置超時(shí)有些差異,已為HttpClient 4.5例:

CloseableHttpClient httpclient = HttpClients.createDefault();  
HttpGet httpGet = new HttpGet("http://stackoverflow.com/");  
RequestConfig requestConfig = RequestConfig.custom()  
        .setConnectTimeout(5000).setConnectionRequestTimeout(1000)  
        .setSocketTimeout(5000).build();  
httpGet.setConfig(requestConfig);  
CloseableHttpResponse response = httpclient.execute(httpGet);  
System.out.println("得到的結(jié)果:" + response.getStatusLine());//得到請(qǐng)求結(jié)果  
HttpEntity entity = response.getEntity();//得到請(qǐng)求回來(lái)的數(shù)據(jù)

推薦你使用HttpClient配合使用Fluent-API:
https://hc.apache.org/httpcom...
設(shè)置超時(shí):

// Execute a GET/POST with timeout settings and return response content as String.
Request.Get("http://somehost/")
        .connectTimeout(1000)
        .socketTimeout(1000)
        .execute().returnContent().asString();
2018年3月16日 14:31