weixin_42450877
Z5zAlex
2011-05-16 22:35
浏览 269
已采纳

java httpclient问题

用httpclient模拟登录一个网站,返回状态码(301或302等),我想不要处理返回状态码,直接用postMethod导向我要的页面,可以不考虑跳转吗?(不是说httpclient自动管理cookie,跳转应该可以忽略吧,哈哈,我的理解),求高手解释啊

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • iihero
    iihero 2011-05-17 06:07
    已采纳

    HttpClient支持自动转向处理,但是象POST和PUT方式这种要求接受后继服务的请求方式,暂时不支持自动转向,因此如果碰到POST方式提交后返回的是301或者302的话需要自己处理。

    参考下例:
    [code="java"]httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    httpClient.getHostConfiguration().setHost("www.xiaonei.com", 80, "http");
    String url = "http://login.xiaonei.com/Login.do";
    PostMethod method = new PostMethod(url);
    NameValuePair email = new NameValuePair( "email" , "" );//邮箱
    NameValuePair password = new NameValuePair( "password" , "" );//密码
    method.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gb2312");
    NameValuePair[] data = { email,password};
    method.setRequestBody(data);
    try {

    httpClient.executeMethod(method);
    Cookie[] cookies=httpClient.getState().getCookies();
    httpClient.getState().addCookies(cookies);
    method.releaseConnection();
    int state = method.getStatusCode();

    // System.out.print(state);
    String newUrl = "";
    if ((state == HttpStatus.SC_MOVED_TEMPORARILY) || (state == HttpStatus.SC_MOVED_PERMANENTLY) || (state == HttpStatus.SC_SEE_OTHER) || (state == HttpStatus.SC_TEMPORARY_REDIRECT)){
    Header header = method2.getResponseHeader("location");

    if(header != null){

    newUrl = header.getValue(); //获得跳转页面地址

    //System.out.println("newUrl: "+newUrl);
    if(newUrl == null || newUrl.equals("")){
    newUrl = "/";
    }
    String urlx=null;
    //以get方式请求跳转页面
    GetMethod getMethod = new GetMethod(newUrl);
    getMethod.setRequestHeader("Cookie",cookies.toString());

    httpClient.excuteMethod(getMethod);

    getMethod.releaseConnection();
    urlx="rundll32 url.dll,FileProtocolHandler "+newUrl;
    Runtime.getRuntime().exec("cmd.exe /c start "+ urlx);[/code]

    同时请参考一下下文,有些地方解释的非常详细。

    http://yefeng.iteye.com/blog/112565

    点赞 评论
  • jianpc
    jianpc 2011-05-17 09:02

    get方式可以自动处理跳转:)

    点赞 评论
  • jianpc
    jianpc 2011-05-17 16:17

    你可以从postmethod里面取得responseHeader中的Set-Cookie字段,然后设置getmethod的requestHeader的Cookie字段。

    点赞 评论
  • qianzhi008
    qianzhi008 2011-05-18 10:05

    楼主是想做删校内人气的工具么 :D

    点赞 评论

相关推荐