2015-04-24 74 views
0

如何設置HttpDefaultClient的暫停時間?如何設置HttpDefaultClient的超時期限?

對於下面的代碼,我想設置一些時間,以便它不會掛起更多的時間。

String methodName = "getResponseFromGlobalService"; 
logger.info(methodName + " started " + "with" + restUrl + "inputs" + jsonObject.toString()); 
DefaultHttpClient httpClient = new DefaultHttpClient(); 
HttpPost postRequest = new HttpPost(restUrl); 
StringBuffer outputDocument = new StringBuffer(); 
StringEntity input1 = new StringEntity(jsonObject.toString()); 
input1.setContentType("application/json"); 
postRequest.setEntity(input1); 
HttpResponse response = httpClient.execute(postRequest); 

if (response.getStatusLine().getStatusCode() != 200) { 
    throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); 
} 

BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); 

String output; 
logger.info("Output from Server .... \n"); 
while ((output = br.readLine()) != null) { 
    outputDocument.append(output); 
} 

JSONObject json = (JSONObject) JSONSerializer.toJSON(outputDocument.toString()); 
logger.info(methodName + " ended "); 
return json; 
+0

重複http://stackoverflow.com/questions/3000214/java-http-client-request-with-defined-timeout – aksappy

+0

的請考慮upvoting或接受的答案,如果它幫助你解決了這個問題。否則,請提供信息。在什麼不工作。謝謝! –

回答

0

如果使用DefaultHttpClient 3.X,那麼這兩種方法,你需要有HttpConnectionParams.html.setConnectionTimeout()HttpConnectionParams.html.setSoTimeout(),分別設置連接超時和插座超時。連接超時是等待連接建立的持續時間,而套接字超時是等待數據的持續時間。

所以,你會使用它們像這樣:

HttpConnectionParams httpParams = new HttpConnectionParams(); 

int connectionTimeout = 30000; // some timeout in milliseconds 
httpParams.setConnectionTimeout(connectionTimeout); 

int socketTimeout = 30000; // some timeout in milliseconds 
httpParams.setSoTimeout(socketTimeout); 

DefaultHttpClient httpClient = new DefaultHttpClient(httpParams); 

現在,如果你使用的是DefaultHttpClient 4.x的,(在這種情況下,你應該使用HttpClientBuilder代替DefaultHttpClient),那麼這些都是方法是將有關:

  1. RequestConfig.Builder.setConnectTimeout
  2. RequestConfig.Builder.setSocketTimeout
  3. RequestConfig.Builder.setConnectionTimeout

下面是一個例子。

int connectTimeout = 50000; 
int requestTimeout = 50000; 
int socketimeout = 50000; 
RequestConfig requestConfig = 
    RequestConfig.custom() 
     .setConnectTimeout(connectTimeout) 
     .setConnectionRequestTimeout(requestTimeout) 
     .setSocketTimeout(socketTimeout) 
     .build(); 
HttpClient httpClient = 
    HttpClientBuilder.create() 
     .setDefaultRequestConfig(requestConfig) 
     .build();