您的位置:首页 > 理论基础 > 计算机网络

commons-httpclient.jar的使用(Cookie的使用 )

2008-03-20 16:09 465 查看
package com.test;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.cookie.CookieSpec;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

public class FormLoginDemo {
 static final String LOGON_STR = "localhost";
 static final int LOGON_PORT = 8080;
 
 public static void main(String[] args) throws Exception{
  HttpClient client = new HttpClient();
  
  client.getHostConfiguration().setHost(LOGON_STR, LOGON_PORT);
  
//   模拟登录页面login.jsp->main.jsp
  PostMethod post = new PostMethod("/a.jsp");
  NameValuePair name = new NameValuePair("name", "Id");
  NameValuePair pass = new NameValuePair("password" , "Id");
  
  post.setRequestBody(new NameValuePair[]{name, pass});
  
  int status = client.executeMethod(post);
  
  System.out.println(post.getResponseBodyAsString());
  post.releaseConnection();
  
  //查看cookie 信息
  CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
  Cookie[] cookies = cookiespec.match(LOGON_STR, LOGON_PORT, "/", 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());
   }
  }
  
  //访问所需的页面main2.jsp
  GetMethod get = new GetMethod("/b.jsp");
  client.executeMethod(get);
  System.out.println(get.getResponseBodyAsString());
  get.releaseConnection();
  
 }
}
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息