org.apache.commons.httpclient

org.apache.commons.httpclient

 

 1   /**
 2      * post 方法
 3      * @param  url
 4      * @param params
 5      * @return
 6      */
 7     public static String post(String url, Object content, String encode) throws Exception {
 8         
 9         byte[] responseBody = null;
10         HttpClient httpclient = new HttpClient();
11         PostMethod httpPost = new PostMethod(url);
12         // 设置连接超时时间(单位毫秒)         
13         httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(60000);
14         // 设置读数据超时时间(单位毫秒)        
15         httpclient.getHttpConnectionManager().getParams().setSoTimeout(60000);
16         try {
17             httpPost.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler(3, false));
18             // servlet
19             if (content instanceof Map) {
20                 @SuppressWarnings("unchecked")
21                 Map<String, String> map = (Map<String, String>)content;
22                 NameValuePair[] param = new NameValuePair[map.size()];
23                 
24                 int index = 0;
25                 for (Map.Entry<String, String> entry : map.entrySet()) {
26                     param[index] = new NameValuePair(entry.getKey(),URLEncoder.encode(entry.getValue(), "GBK"));
27                 }
28                 
29                 httpPost.setRequestBody(param);
30             }
31             // rest
32             else {
33                 httpPost.setRequestEntity(new StringRequestEntity((String)content,"plain/text", encode));
34             }
35             
36             // post
37             int statusCode = httpclient.executeMethod(httpPost);
38             // success
39             if (statusCode == HttpStatus.SC_OK) {
40                 responseBody = httpPost.getResponseBody();
41             }
42             // failure
43             else {
44                 
45             }
46         } catch (HttpException e) {
47             throw new Exception(e.getMessage());
48         } catch (IOException e) {
49             throw new Exception(e.getMessage());
50         } catch (Exception e) {
51             throw new Exception(e.getMessage());
52         } finally {
53             httpPost.releaseConnection();
54         }
55         return new String(responseBody, encode);
56     }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值