2008年10月16日 星期四

[Java]Use HttpClient Login Websites

要讓以下程式run起來,必須先要...
Step1.取得其相關使用到的API --- 點我下載
Step2.下載回來後,要懂得 Set ClassPath
Step3.另外可以參考這三篇,裡頭的內容都寫的超詳細的。
- Link1
- Link2
Step4.如果不幸的,Step3的連結網頁失效了。可以參考我備份的版本。
- My backup Link1
- My backup Link2
- My backup Link3

//Remember Set The Class Path


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" , "" );
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();

}
}


不錯的範例網站:
http://www.java2s.com/Code/Java/Apache-Common/GetCookievalueandsetcookievalue.htm

沒有留言:

張貼留言