Java实现模拟Client
在java中模拟Client有很多手段, 比如: 直接使用jdk中内嵌的URLConnection来实现; 使用第三方的开发包来实现(Apache的HttpClient).
现在, 介绍一下使用Apache的HttpClient的基本过程:
1. 创建HttpClient实例;
client = new HttpClient();
2. 创建某种连接方式(GetMethod, PutMethod, PostMethod, DeleteMethod);
method = new GetMethod(url);
3. 设置一些参数;
设置cookie: method.addRequestHeader("Cookie", cookie);
设置传入的数据: method.setRequestEntity(byteArrayRequestEntity)
4. 调用HttpClient.excute(method)方法
5. 获取返回结果并进行处理.
获取Stream格式的数据: method.getResponseBodyAsStream();
获取cookie: method.getResponseHeader("Set-Cookie");
6. 释放连接(必须做).
method.releaseConnection();
注意:
如果在返回的结果中需要获取Session的时候(存储在Cookie中), 服务端在处理请求的过程中需要getSession才能起作用,不知道为什么, 比较奇怪!
1 楼 skydream 2007-12-30 不建议继续使用Apache的HttpClient,Apache已经准备放弃HttpClient3.0的继续开发,重新发布了一个全新的HttpComponents,作为HttpClient3.0的下一个版本。而且,不兼容,基本是推翻了重来。当然目前HttpComponents还不是很成熟,但是肯定会在不远的将来完全替代HttpClient3.0。
HttpComponents的架构是全新设计的,比HttpClient3.0好的多。
看这里: http://hc.apache.org/
The Apache HttpComponents project is charged with developing and maintaining Commons HttpClient. Commons HttpClient is the current stable library of choice for most users. Commons HttpClient 3 will be maintained until Apache HttpClient 4 is deemed stable enough to supersede it for use in production. 2 楼 sunyujia 2007-12-31 这里和csdn果然不同啊,csdn小菜太多了,这里牛人比较多呵呵,看来以后的来这学习了。
能介绍一下HttpClient3的主要应用场景吗?谢谢,我没用过只是一直知道这个包。 3 楼 swantt 2008-01-02 我主要用的是HTMLUNIT也挺好用的.