HttpClient的cookie

package com.huawe;

import java.io.IOException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

public class Cookies {

 public static void main(String[] args) {
  HttpClient client = new DefaultHttpClient();

  // 創建一個Cookie倉庫
  CookieStore store = new BasicCookieStore();

  // 創建上下文環境
  HttpContext context = new BasicHttpContext();

  context.setAttribute(ClientContext.COOKIE_STORE, store);

  HttpGet httpget = new HttpGet("http://www.google.com/");

  System.out.println("executing request " + httpget.getURI());
  try {
   HttpResponse response = client.execute(httpget, context);
   HttpEntity entity = response.getEntity();

   System.out.println("----------------------------------------");
   System.out.println(response.getStatusLine());

   if (entity != null) {
    System.out.println("Response content length: "
      + entity.getContentLength());
   }
   List<Cookie> cookies = store.getCookies();

   for (int i = 0; i < cookies.size(); i++) {
    System.out.println("Local cookie: " + cookies.get(i));
   }

   // Consume response content
   if (entity != null) {
    entity.consumeContent();

   }

   System.out.println("----------------------------------------");
   client.getConnectionManager().shutdown();

  } catch (ClientProtocolException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  } catch (IOException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  }

 }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章