在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才能起作用,不知道为什么, 比较奇怪!
现在, 介绍一下使用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才能起作用,不知道为什么, 比较奇怪!