org.apache.commons.httpclient.HttpClient 设置数据接收超时

1.使用方法


/**
	 * http post请求后返回的字符串信息
	 * 
	 * @param url
	 *            请求的url地址
	 * @param data
	 *            请求参数各个表单域的值NameValuePair
	 * @return
	 */
	public static String httpPost(String url, NameValuePair[] data) throws Exception{
		String returnStr = "";
		PostMethod postMethod = new PostMethod(url);
		try {
			postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");


			// url的连接等待超时时间设置
			client.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);

			// 读取数据超时时间设置
			client.getHttpConnectionManager().getParams().setSoTimeout(soTimeout);

			// 将表单的值放入postMethod中
			postMethod.setRequestBody(data);

			// 执行postMethod
			int statusCode = client.executeMethod(postMethod);

			for (Header header : postMethod.getResponseHeaders()) {
				System.out.println(header.getName() + " : " + header.getValue());
			}
			// 判断回复响应状态是否正常
			if (statusCode == HttpStatus.SC_OK) {
				returnStr = new String(postMethod.getResponseBodyAsString());
			}
		} catch (SocketTimeoutException ex) {
			log.error("http post请求异常! 请求url:" + url);
			log.error(ex);
			throw new SocketTimeoutException("响应超时:"+ex.getMessage()+url);
		}  catch (Exception ex) {
			log.error("http post请求异常! 请求url:" + url);
			log.error(ex);
			throw new Exception();
		} finally {
			// 释放连接
			if (postMethod != null) {
				try {
					postMethod.releaseConnection();
				} catch (final Exception e) {
				}
			}
		}
		return returnStr;
	}

2.调用

Map req=new HashMap();
	try {
			String rs=HttpClientUtils.httpPostSPP(SPPUrl,HttpClientUtils.generatnamevaluepair(req));
			return JSONObject.fromObject(rs);
		}catch (SocketTimeoutException e) {
			logger.info(e.getMessage());
			throw new SocketTimeoutException(e.getMessage());
		} catch (Exception e) {
			throw new UnCaughtException();
		}



你可能感兴趣的:(菜鸟基层)