org.apache.commons.httpclient

时间:2023-03-09 03:18:17
org.apache.commons.httpclient

org.apache.commons.httpclient

   /**
* post 方法
* @param url
* @param params
* @return
*/
public static String post(String url, Object content, String encode) throws Exception { byte[] responseBody = null;
HttpClient httpclient = new HttpClient();
PostMethod httpPost = new PostMethod(url);
// 设置连接超时时间(单位毫秒)
httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(60000);
// 设置读数据超时时间(单位毫秒)
httpclient.getHttpConnectionManager().getParams().setSoTimeout(60000);
try {
httpPost.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler(3, false));
// servlet
if (content instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, String> map = (Map<String, String>)content;
NameValuePair[] param = new NameValuePair[map.size()]; int index = 0;
for (Map.Entry<String, String> entry : map.entrySet()) {
param[index] = new NameValuePair(entry.getKey(),URLEncoder.encode(entry.getValue(), "GBK"));
} httpPost.setRequestBody(param);
}
// rest
else {
httpPost.setRequestEntity(new StringRequestEntity((String)content,"plain/text", encode));
} // post
int statusCode = httpclient.executeMethod(httpPost);
// success
if (statusCode == HttpStatus.SC_OK) {
responseBody = httpPost.getResponseBody();
}
// failure
else { }
} catch (HttpException e) {
throw new Exception(e.getMessage());
} catch (IOException e) {
throw new Exception(e.getMessage());
} catch (Exception e) {
throw new Exception(e.getMessage());
} finally {
httpPost.releaseConnection();
}
return new String(responseBody, encode);
}