2011-11-10 10 views
10

Sto riscontrando problemi nell'invio di cookie come parte di un get http. Per prima cosa vado a una pagina di accesso all'interno di una webview che mi dà un cookie. Ho controllato e il cookie è stato memorizzato nel CookieManager. Quindi utilizzo una BasicHttpRequest per ottenere un determinato URL dallo stesso dominio. Mi aspetterei che il cookie che ho ricevuto dal login sia allegato alle mie intestazioni per l'ottenimento, ma guardandolo in Wireshark non è lì. Googled e letto un sacco di domande simili e hanno fatto in modo che:Condivisione di cookie da Webview con BasicHttpRequest su Android

  • Sto usando il CookieSyncManager così mi auguro i miei biscotti dalla sessione persisterebbe. Non penso che sia un problema con CookieSyncManager essere asincrono perché continuo a colpire l'URL ogni 5 secondi e il cookie non viene mai aggiunto.
  • Sospetto di dover comunicare la mia richiesta http sul mio negozio di cookie, ma le soluzioni che ho cercato su Google non vengono compilate per me. Sembra che voglia fare qualcosa che assomigli a context.setAttribute (ClientContext.COOKIE_STORE, this.cookieStore), ma non riesco a capire come ottenere il CookieStore predefinito dal CookieManager. Qualche codice sembra chiamare cookieManager.getCookieStore() ma questo non viene compilato per me su Android. Guardando i documenti non riesco a vedere un modo per ottenere il CookieStore che sembra folle - mi manca qualcosa di ovvio?

Il mio codice per avviare la pagina di accesso nel mio WebView assomiglia:

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); 

Poi il mio codice per controllare il cookie c'è assomiglia:

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; 
} 

e per rendere realtà la richiesta http che faccio

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; 
} 

Grazie per la lettura questo lontano! Qualsiasi suggerimento ben accetto,

Amy

+0

Hai provato params.setParameter ("cookie", cookie)? mentre cookie è il cookie valido dal tuo CookieStore. –

+0

Ciao Franziskus, ho appena provato params.setParameter ("cookie", cookie), e posso vedere che params ora ha 5 voci, ma la parte del cookie non fa mai entrare in http come visto usando Wireshark. –

risposta

3

Collegamento cookie è finalmente lavorare per me! Potrei non averlo fatto nel modo più semplice, ma almeno funziona. Il mio grande passo avanti è stato il download e il collegamento delle sorgenti Android, così da poter passare e vedere cosa stava succedendo. Qui ci sono le istruzioni http://blog.michael-forster.de/2008/12/view-android-source-code-in-eclipse.html - scorrere verso il basso e leggere il commento di Volure per il download più semplice. Consiglio vivamente di farlo se sviluppi su Android.

Ora sul codice dei cookie di lavoro - la maggior parte delle modifiche erano nel codice che in realtà mi porta la mia pagina web - Ho dovuto impostare un COOKIE_STORE e un COOKIESPEC_REGISTRY. Poi ho anche dovuto cambiare il mio tipo di connessione perché il codice cookie proiettava in un 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; 
} 

Il mio codice per impostare le mie vite biscotto nella stessa classe come getMeAWebpage() assomiglia:

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... 
} 

Spero davvero che questo aiuti se hai problemi simili - Mi sento come se stessi sbattendo la testa contro un muro per un paio di settimane! Ora per una meritata tazza celebrativa di tè: o)

Problemi correlati