`
LifeFree
  • 浏览: 60803 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

使用Aache Commons HttpClient 要注意的一个问题

阅读更多
apache 的东西可以说是我编程用的最多的东西了。最近做的一个程序因为要手动Post数据给
  一个外部URL,当时觉得如果直接调用java的API,太靠近底层了,要是要扩展一下,要设个代理等
  处理起来麻烦了点。这样的功能大家都要用到,
  猜想肯定有现成的更高级的api,直接在我们的项目的lib里翻了翻,发现有commons-httpclient-3.0-rc3.jar
  的jar,在apache上一看正是我要的东西,apache的user guide 写着:
 
 
java 代码
 
  1. PostMethod post = new PostMethod("http://jakarata.apache.org/");  
  2. NameValuePair[] data = {  
  3.   new NameValuePair("user""joe"),  
  4.   new NameValuePair("password""bloggs")  
  5. };  
  6. post.setRequestBody(data);  
  7. // execute method and handle any error responses.  
  8. ...  
  9. InputStream in = post.getResponseBodyAsStream();  
  10. // handle response.  

       
呵呵,这不就是我想要的嘛。马上写了个测试程序,调用后发现返回的输入流
(InputStream in) 为空,把url改成"www.google.com"返回的还是空,上网google
一把,发现台湾的javaworld网站也有人提出这个问题。

  程序就这么几行,改来改去都不行。最后在HttpClient的apidoc MultipartRequestEntity
  类的说明中找到一个的例子:
 
java 代码
 
  1. File f = new File("/path/fileToUpload.txt");  
  2.   PostMethod filePost = new PostMethod("http://host/some_path");  
  3.   Part[] parts = {  
  4.       new StringPart("param_name""value"),  
  5.       new FilePart(f.getName(), f)  
  6.   };  
  7.   filePost.setRequestEntity(  
  8.       new MultipartRequestEntity(parts, filePost.getParams())  
  9.       );  
  10.   HttpClient client = new HttpClient();  
  11.   int status = client.executeMethod(filePost);  

 
  这个例子最后两行多了一个client.executeMethod(filePost)的调用,
  于是把最后两行拿来改改,放到上个例子的"InputStream in = post.getResponseBodyAsStream();"一行的
  前面。终于雨过天晴拿到了返回输入流。
 
  经过测试如果不进行executeMethod()的调用是拿不到输入流的,真不清楚apache userguide别人是怎么运行成功
  的难道就我比较笨不知到先调用executeMethod() ??

  ps: 完整的程序需要进行异常的捕获与处理,post需要调用post.releaseConnection()来释放连接。
分享到:
评论
3 楼 weiqingfei 2007-06-21  
不执行连请求都发不出去呀,你都没捕捉以下传送数据么
2 楼 dwangel 2007-06-21  
感觉显然你没有仔细看user guide.
有下面的话,

The examples on the following pages are not complete and are only used to highlight the important features that are unique to each method. For complete examples, please refer to the sample code.

同时sample code的连接也给出来了。
估计后期改动比较大,开发组自己都不确定以后会怎样调用了。
1 楼 gfh21cn 2007-06-21  
不错,谢谢楼主

相关推荐

Global site tag (gtag.js) - Google Analytics