HttpClient 连接要设置超时

来源:互联网 发布:网络兼职日结免费入职 编辑:程序博客网 时间:2024/05/17 06:22
private static void postWithJson(Map<String, String> map) {
String respMessage = "";
HttpClient httpClient = null;
PostMethod postMethod = null;


try {
int i = 0;
httpClient = new HttpClient();
postMethod = new PostMethod(DPS_LOGGER_PUBLIC_SERVICE_URL);
postMethod.getParams().setParameter(
HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
HttpConnectionManagerParams managerParams = httpClient 
   .getHttpConnectionManager().getParams(); 
 // 设置连接超时时间(单位毫秒) 
 managerParams.setConnectionTimeout(9000); 
 // 设置读数据超时时间(单位毫秒) 
 managerParams.setSoTimeout(12000); 
NameValuePair[] data = null;
if (map != null && map.size() > 0) {
data = new NameValuePair[map.size()];
for (Map.Entry<String, String> entry : map.entrySet()) {
data[i++] = new NameValuePair(entry.getKey(),
entry.getValue());
}
postMethod.setRequestBody(data);
}


int status = httpClient.executeMethod(postMethod);
if (status == HttpStatus.SC_OK) {
InputStream inputStream = postMethod.getResponseBodyAsStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
inputStream, "UTF-8"));
String str = "";
StringBuffer stringBuffer = new StringBuffer();
while ((str = br.readLine()) != null) {
stringBuffer.append(str);
}
respMessage = stringBuffer.toString();
} else {
String resultText = postMethod.getStatusLine().toString();
respMessage = "{\"resultCode\":10,\"resultText\":\""
+ resultText + "\",\"resultContent\":null}";
}


} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (postMethod != null) {
postMethod.releaseConnection();
}
}
}
0 0