1 import org.apache.commons.httpclient.*;
2 import org.apache.commons.httpclient.cookie.*;
3 import org.apache.commons.httpclient.methods.*;
4
5 public class HTTPSample {
6
7 public static void main(String[] arg) throws Exception {
8
9 String server = "localhost";
10 int port = 80;
11
12 // クライアントの生成
13 HttpClient client = new HttpClient(); ←(1)
14 client.getHostConfiguration().setHost(server, port, "http"); ←(1)
15 client.getState().setCookiePolicy(CookiePolicy.COMPATIBILITY); ←(1)
16
17 // 認証ページを通過し、トップページにアクセス
18 PostMethod top = new PostMethod( "/club/member/top.html" ); ←(2)
19 NameValuePair[] parameters = new NameValuePair[2]; ←(2)
20 parameters[0] = new NameValuePair("username", "user"); ←(2)
21 parameters[1] = new NameValuePair("password", "password"); ←(2)
22 top.setRequestBody( parameters ); ←(2)
23
24 client.executeMethod(top); ←(3)
25 // 取得したクッキーを表示
26 Cookie[] cookies = client.getState().getCookies(server, port, ←(3)
27 "/club", false ); ←(3)
28 for (int i=0; i<cookies.length; i++) { ←(3)
29 System.out.println(cookies[i].toString()); ←(3)
30 } ←(3)
31 System.out.println( top.getResponseBodyAsString() ); ←(3)
32 top.releaseConnection(); ←(3)
33
34 // infoページにアクセス
35 GetMethod info = new GetMethod( "/club/member/info.html" ); ←(4)
36 int status = client.executeMethod(info); ←(4)
37 String body = info.getResponseBodyAsString(); ←(4)
38 System.out.println( "status: " + status + "\n"); ←(4)
39 System.out.println( body ); ←(4)
40 info.releaseConnection(); ←(4)
41 }
42 }
|