hwp1023
JC_陈
2012-11-26 16:17
浏览 368
已采纳

httpClient与服务器建立连接时cookie传递问题

httpClient与服务器建立连接时cookie传递问题,使用httpGet或httpPost方式怎么传cookie给服务器?

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

1条回答 默认 最新

  • iteye_5246
    iteye_5246 2012-11-26 16:27
    已采纳

    送你个demo
    [code="java"]package http.demo;
    import org.apache.commons.httpclient.*;
    import org.apache.commons.httpclient.cookie.*;
    import org.apache.commons.httpclient.methods.*;
    /**

    • 用来演示登录表单的示例
    • @author Liudong */ public class FormLoginDemo { static final String LOGON_SITE = "localhost" ; static final int LOGON_PORT = 8080; public static void main(String[] args) throws Exception{ HttpClient client = new HttpClient(); client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT); // 模拟登录页面 login.jsp->main.jsp PostMethod post = new PostMethod( "/main.jsp" ); NameValuePair name = new NameValuePair( "name" , "ld" ); NameValuePair pass = new NameValuePair( "password" , "ld" ); 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_SITE, 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 GetMethodget=newGetMethod("/main2.jsp"); client.executeMethod(get); System.out.println(get.getResponseBodyAsString()); get.releaseConnection(); } }[/code]
    点赞 评论

相关推荐