您的位置:首页 > 理论基础 > 计算机网络

HttpClient 连接要设置超时

2015-05-05 14:50 211 查看
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();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: