2011-11-10 20 views
10

Tôi gặp sự cố khi gửi cookie như một phần của http get. Trước tiên, tôi đi đến một trang đăng nhập trong một webview mang lại cho tôi một cookie. Tôi đã kiểm tra và cookie đang được lưu trữ trong CookieManager. Sau đó, tôi sử dụng BasicHttpRequest để lấy một URL cụ thể từ cùng một miền. Tôi hy vọng cookie mà tôi nhận được từ thông tin đăng nhập sẽ được đính kèm vào tiêu đề của tôi để nhận được, nhưng nhìn vào nó trong Wireshark nó không có ở đó. Tôi đã googled và đọc rất nhiều câu hỏi tương tự và đã đảm bảo rằng:Chia sẻ cookie từ chế độ xem web với BasicHttpRequest trên Android

  • Tôi đang sử dụng CookieSyncManager vì vậy tôi hy vọng cookie của tôi từ phiên sẽ vẫn tồn tại. Tôi không nghĩ rằng đó là một vấn đề với CookieSyncManager là không đồng bộ vì tôi tiếp tục nhấn URL mỗi 5 giây và cookie không bao giờ được thêm vào.
  • Tôi cho rằng tôi cần phải thông báo yêu cầu http về cửa hàng cookie của tôi, nhưng các giải pháp tôi đã googled không biên dịch cho tôi. Có vẻ như tôi muốn làm một cái gì đó trông giống như context.setAttribute (ClientContext.COOKIE_STORE, this.cookieStore), nhưng tôi không thể tìm ra cách lấy CookieStore mặc định từ CookieManager. Một số mã dường như gọi cookieManager.getCookieStore() nhưng điều đó không biên dịch cho tôi trên Android. Nhìn vào các tài liệu tôi không thể nhìn thấy một cách để có được CookieStore mà dường như điên - tôi thiếu một cái gì đó hiển nhiên?

Mã của tôi để bắt đầu lên trang đăng nhập trong webview của tôi trông giống như:

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    // use cookies to remember a logged in status 
    CookieSyncManager.createInstance(this); 
    CookieSyncManager.getInstance().startSync(); 

    //not sure if I need to do this 
    CookieManager cookie_manager = CookieManager.getInstance(); 
    cookie_manager.setAcceptCookie(true); 

    webview = new WebView(this); 
    webview.getSettings().setJavaScriptEnabled(true); 
    webview.setWebViewClient(new HelloWebViewClient()); // if user clicks on a url we need to steal that click, also steal the back button 
    webview.loadUrl("http://"+my_server+"/api/v1/login"); 
    setContentView(webview); 

Sau đó, mã của tôi để kiểm tra cookie là có trông giống như:

public static boolean CheckAuthorised() { 
    CookieSyncManager.getInstance().sync(); 
    CookieManager cookie_manager = CookieManager.getInstance(); 

    String cookie_string = cookie_manager.getCookie("http://"+my_server+"/api/v1/login"); 
    System.out.println("lbp.me cookie_string: " + cookie_string); 

    if(cookie_string != null) 
    { 
     String[] cookies = cookie_string.split(";"); 
     for (String cookie : cookies) 
     { 
      if(cookie.matches("API_AUTH=.*")) 
      { 
       // maybe we need to store the cookie for the root of the domain? 
       cookie_manager.setCookie("http://"+my_server, cookie_string); 
       // maybe we need to store the cookie for the url we're actually going to access? 
       cookie_manager.setCookie("http://"+my_server+"/api/v1/activity", cookie_string);  

       CookieSyncManager.getInstance().sync(); 
       return true; 
      } 
     } 
    } 

    return false; 
} 

Và để thực sự làm yêu cầu http tôi làm

public static HttpResponse getMeAWebpage(String host_string, int port, String url) 
     throws Exception { 
    HttpParams params = new BasicHttpParams(); 
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); 
    HttpProtocolParams.setContentCharset(params, "UTF-8"); 
    HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1"); 
    HttpProtocolParams.setUseExpectContinue(params, true); 

    BasicHttpProcessor httpproc = new BasicHttpProcessor(); 
    // Required protocol interceptors 
    httpproc.addInterceptor(new RequestContent()); 
    httpproc.addInterceptor(new RequestTargetHost()); 
    // Recommended protocol interceptors 
    httpproc.addInterceptor(new RequestConnControl()); 
    httpproc.addInterceptor(new RequestUserAgent()); 
    httpproc.addInterceptor(new RequestExpectContinue()); 

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); 

    HttpContext context = new BasicHttpContext(null); 
    // HttpHost host = new HttpHost("www.svd.se", 80); 
    HttpHost host = new HttpHost(host_string, port); 

    DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); 
    ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy(); 

    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); 
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); 
    //CookieManager cookie_manager = CookieManager.getInstance(); 
    //CookieStore cookie_store = cookie_manager.getCookieStore(); //The method getCookieStore() is undefined for the type CookieManager 
    //context.setAttribute(ClientContext.COOKIE_STORE, cookie_store); 

    HttpResponse response = null; 

    try { 
     if (!conn.isOpen()) { 
      Socket socket = new Socket(host.getHostName(), host.getPort()); 
      conn.bind(socket, params); 
     } 

     BasicHttpRequest request = new BasicHttpRequest("GET", url); 
     System.out.println(">> Request URI: " 
       + request.getRequestLine().getUri()); 
     System.out.println(">> Request: " 
       + request.getRequestLine()); 

     request.setParams(params); 
     httpexecutor.preProcess(request, httpproc, context); 
     response = httpexecutor.execute(request, conn, context); 
     response.setParams(params); 
     httpexecutor.postProcess(response, httpproc, context); 

     String ret = EntityUtils.toString(response.getEntity()); 
     System.out.println("<< Response: " + response.getStatusLine()); 
     System.out.println(ret); 
     System.out.println("=============="); 
     if (!connStrategy.keepAlive(response, context)) { 
      conn.close(); 
     } else { 
      System.out.println("Connection kept alive..."); 
     } 
    } catch(UnknownHostException e) { 
     System.out.println("UnknownHostException"); 
    } catch (HttpException e) { 
     System.out.println("HttpException"); 
    } finally { 
     conn.close(); 
    } 

    return response; 
} 

Cảm ơn bạn đã đọc g này xa! Mọi góp ý biết ơn nhận được,

Amy

+0

Bạn đã thử params.setParameter ("cookie", cookie) chưa? trong khi cookie là Cookie hợp lệ từ CookieStore của bạn. –

+0

Hi Franziskus, tôi vừa thử params.setParameter ("cookie", cookie), và tôi có thể thấy rằng params hiện có 5 mục, nhưng phần cookie không bao giờ làm cho nó vào http nhận được như được thấy bằng cách sử dụng Wireshark. –

Trả lời

3

Gắn cookie cuối cùng đang làm việc cho tôi! Tôi có thể đã không làm điều đó một cách dễ dàng nhất, nhưng ít nhất nó hoạt động. Bước đột phá lớn của tôi là tải xuống và đính kèm các nguồn Android, để tôi có thể xem qua và xem điều gì đang xảy ra. Có hướng dẫn ở đây http://blog.michael-forster.de/2008/12/view-android-source-code-in-eclipse.html - cuộn xuống và đọc nhận xét từ Volure để tải xuống đơn giản nhất. Tôi rất khuyên bạn nên làm điều này nếu bạn đang phát triển trên Android.

Bây giờ, trên mã cookie đang hoạt động - hầu hết các thay đổi đều có trong mã thực sự đưa tôi đến trang web của tôi - tôi phải thiết lập COOKIE_STORE và COOKIESPEC_REGISTRY. Sau đó, tôi cũng đã phải thay đổi kiểu kết nối của tôi vì mã cookie được đúc nó vào một ManagedClientConnection:

public static HttpResponse getMeAWebpage(String host_string, int port, String url) 
     throws Exception { 
    HttpParams params = new BasicHttpParams(); 
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); 
    HttpProtocolParams.setContentCharset(params, "UTF-8"); 
    HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1"); 
    HttpProtocolParams.setUseExpectContinue(params, true); 
    //params.setParameter("cookie", cookie); 

    BasicHttpProcessor httpproc = new BasicHttpProcessor(); 
    // Required protocol interceptors 
    httpproc.addInterceptor(new RequestContent()); 
    httpproc.addInterceptor(new RequestTargetHost()); 
    // Recommended protocol interceptors 
    httpproc.addInterceptor(new RequestConnControl()); 
    httpproc.addInterceptor(new RequestUserAgent()); 
    httpproc.addInterceptor(new RequestExpectContinue()); 
    httpproc.addInterceptor(new RequestAddCookies()); 


    HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); 

    HttpContext context = new BasicHttpContext(null); 
    // HttpHost host = new HttpHost("www.svd.se", 80); 
    HttpHost host = new HttpHost(host_string, port); 
    HttpRoute route = new HttpRoute(host, null, false); 

    // Create and initialize scheme registry 
    SchemeRegistry schemeRegistry = new SchemeRegistry(); 
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); 
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); 

    SingleClientConnManager conn_mgr = new SingleClientConnManager(params, schemeRegistry); 
    ManagedClientConnection conn = conn_mgr.getConnection(route, null /*state*/); 
    ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy(); 

    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); 
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); 

    CookieStore cookie_store = new BasicCookieStore(); 
    cookie_store.addCookie(cookie); 
    context.setAttribute(ClientContext.COOKIE_STORE, cookie_store); 

    // not sure if I need to add all these specs, but may as well 
    CookieSpecRegistry cookie_spec_registry = new CookieSpecRegistry(); 
    cookie_spec_registry.register(
      CookiePolicy.BEST_MATCH, 
      new BestMatchSpecFactory()); 
    cookie_spec_registry.register(
      CookiePolicy.BROWSER_COMPATIBILITY, 
      new BrowserCompatSpecFactory()); 
    cookie_spec_registry.register(
      CookiePolicy.NETSCAPE, 
      new NetscapeDraftSpecFactory()); 
    cookie_spec_registry.register(
      CookiePolicy.RFC_2109, 
      new RFC2109SpecFactory()); 
    cookie_spec_registry.register(
      CookiePolicy.RFC_2965, 
      new RFC2965SpecFactory()); 
    //cookie_spec_registry.register(
    //  CookiePolicy.IGNORE_COOKIES, 
    //  new IgnoreSpecFactory()); 
    context.setAttribute(ClientContext.COOKIESPEC_REGISTRY, cookie_spec_registry); 

    HttpResponse response = null; 

    try { 
     if (!conn.isOpen()) { 
      conn.open(route, context, params); 
     } 

     BasicHttpRequest request = new BasicHttpRequest("GET", url); 
     System.out.println(">> Request URI: " 
       + request.getRequestLine().getUri()); 
     System.out.println(">> Request: " 
       + request.getRequestLine()); 

     request.setParams(params); 
     httpexecutor.preProcess(request, httpproc, context); 
     response = httpexecutor.execute(request, conn, context); 
     response.setParams(params); 
     httpexecutor.postProcess(response, httpproc, context); 

     String ret = EntityUtils.toString(response.getEntity()); 
     System.out.println("<< Response: " + response.getStatusLine()); 
     System.out.println(ret); 
     System.out.println("=============="); 
     if (!connStrategy.keepAlive(response, context)) { 
      conn.close(); 
     } else { 
      System.out.println("Connection kept alive..."); 
     } 
    } catch(UnknownHostException e) { 
     System.out.println("UnknownHostException"); 
    } catch (HttpException e) { 
     System.out.println("HttpException"); 
    } finally { 
     conn.close(); 
    } 

    return response; 
} 

Mã của tôi để thiết lập cuộc sống cookie của tôi trong lớp giống như getMeAWebpage() trông giống như:

public static void SetCookie(String auth_cookie, String domain) 
{ 
    String[] cookie_bits = auth_cookie.split("="); 
    cookie = new BasicClientCookie(cookie_bits[0], cookie_bits[1]); 
    cookie.setDomain(domain); // domain must not have 'http://' on the front 
    cookie.setComment("put a comment here if you like describing your cookie"); 
    //cookie.setPath("/blah"); I don't need to set the path - I want the cookie to apply to everything in my domain 
    //cookie.setVersion(1); I don't set the version so that I get less strict checking for cookie matches and am more likely to actually get the cookie into the header! Might want to play with this when you've got it working... 
} 

Tôi thực sự hy vọng điều này sẽ giúp ích nếu bạn gặp phải các vấn đề tương tự - tôi cảm thấy như mình đã đập đầu vào tường trong một vài tuần! Giờ đây, để có một tách trà đáng mừng: o)

Các vấn đề liên quan