HttpClient如何让服务器知道是哪个session
本帖最后由 AWUSOFT 于 2011-01-04 13:09:48 编辑 有一个网站,是用来查询的,输入一个单号,上边有验证码的.查了很多的验证码破解的都没有成功,就想到手动输入验证码,想使用httpclient来实现
先用httpclient访问,再访问其中生成验证码图片的servlet,得到图片,保存到服务器上,显示出来,浏览中输入验证码,然后再使用httpclient提交.
两次的提交是如何让这个网站知道是两次是同一个会话呢?附加Cookie吗?要怎么加呢?
以下为相关的一些代码
import java.io.IOException;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.PostMethod;
public class HttpClientTest1 {
public static void main(String[] args) {
HttpClient client = new HttpClient();
String url = "首页地址";//得到sessionID
PostMethod method = new PostMethod(url);
method.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
try {
client.executeMethod(method);
String body = method.getResponseBodyAsString();
System.out.println(body);
Cookie[] cookie = client.getState().getCookies();
url = "提交URL";
method = new PostMethod(url);
for(int ii=0;ii<cookie.length;ii++)
{
Cookie cook = cookie[ii];
client.getState().addCookie(cook);
}
method.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
body = method.getResponseBodyAsString();
System.out.println("----"+body);
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}