`
ainn2006
  • 浏览: 64481 次
  • 来自: ...
社区版块
存档分类
最新评论

httpclient向服务器POST XML字符串

 
阅读更多
一、使用 HttpClient 需要如下做法



1、 创建 HttpClient 的实例

2、 创建POST连接方法的实例

3、 调用client的 execute 方法来执行第二步中创建好的 method 实例

4、 读 response

5、 释放连接。无论执行方法是否成功,都必须释放连接

6、 对得到后的内容进行处理



二、创建处理上传处理的类UploadManager.java
Java代码  收藏代码

    import java.util.ArrayList; 
    import java.util.List; 
    import java.util.regex.Pattern; 
     
    import org.apache.commons.httpclient.HttpClient; 
    import org.apache.commons.httpclient.NameValuePair; 
    import org.apache.commons.httpclient.methods.PostMethod; 
     
    public class UploadManager { 
        HttpClient client = new HttpClient(); 
        PostMethod method = new PostMethod(){ 
              public String getRequestCharSet() { 
                return "GBK"; 
        }}; 
             
        List<NameValuePair> params = new ArrayList<NameValuePair>(); 
        String host; 
        String path; 
        int port; 
     
        public UploadManager setURL(String host, String path, int port) { 
            this.host = host; 
            this.path = path; 
            this.port = port; 
            client.getHostConfiguration().setHost(host, port, "http"); 
            method.setPath(path); 
            return this; 
        } 
     
        public UploadManager addParam(String key, String value) { 
            params.add(new NameValuePair(key, value)); 
            return this; 
        } 
     
        public boolean upload() { 
            try { 
                    //将NameValuePair表单的值放入postMethod中            
                    method.setRequestBody(params.toArray(new NameValuePair[params.size()])); 
                int statusCode = client.executeMethod(method); 
                String response = method.getResponseBodyAsString(); 
                if(response.startsWith("SUCESS")) 
                    return true; 
            }catch (HttpException e) { 
                           //发生致命的异常,可能是协议不对或者返回的内容有问题 
                           System.out.println("Please check your provided http address!"); 
                           e.printStackTrace(); 
                   }catch (IOException e) { 
                           //发生网络异常 
                e.printStackTrace(); 
            } finally { 
                params.clear(); 
                method.releaseConnection(); 
            } 
            return false; 
        } 
    } 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics