如何设置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 :(得分: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),那么这些是相关的方法:
以下是一个例子。
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();