[转载]使用httpclient下载需要登录的网页

作者: ldsea 分类: 程序生活 发布时间: 2009-04-11 16:56

[code]import java.io.IOException;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.cookie.*;
import org.apache.commons.httpclient.methods.*;

public class JClientLoginTest {
public static void main(String[] args) throws HttpException, IOException {
  HttpClient client = new HttpClient();
  client.getHostConfiguration().setHost( "bbs.cpcw.com" , 80, "http" );

  PostMethod post = new PostMethod( "/logging.php?action=login" );
  NameValuePair name = new NameValuePair( "username" , "dongle2001" );
  NameValuePair pass = new NameValuePair( "password" , "1a9i8h1a" );
  NameValuePair quest = new NameValuePair( "questionid" , "0" );
  NameValuePair answer = new NameValuePair( "answer" , "" );[www.iocblog.net 来源]
  NameValuePair cookietime = new NameValuePair( "cookietime" , "315360000" );
  NameValuePair submit = new NameValuePair( "loginsubmit" , "提   交" );
  post.setRequestBody( new NameValuePair[]{name,pass,quest,answer,cookietime,submit});
  int status = client.executeMethod(post);
  post.releaseConnection();

  CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
  Cookie[] cookies = cookiespec.match("bbs.cpcw.com", 80, "/" , false , client.getState().getCookies());
  if (cookies.length == 0) {
     System.out.println( "None" );
   } else {
   for ( int i = 0; i < cookies.length; i++) {
      System.out.println(cookies[i].toString());
   }
  }

  GetMethod get=new GetMethod("/viewthread.php?tid=883329");
  client.executeMethod(get);
  String response = new String(get.getResponseBodyAsString().getBytes("8859-1"));
  System.out.println(response);
  get.releaseConnection();

}
}[/code]

一条评论
  • bUbuntu

    2010年2月23日 00:28

    不错!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注