【问题标题】:Android POST data and COOKIESAndroid POST 数据和 COOKIES
【发布时间】:2010-06-30 19:32:22
【问题描述】:

我有一个用户名作为密码,我需要将其作为 android 应用程序的一部分发送到网站(是的,它是 https),一旦通过 POST 提交给服务器,服务器应该返回 cookie。我需要能够捕获这些 cookie,并允许在我设置的 web 视图中访问它们。

我该怎么做?

谢谢

【问题讨论】:

    标签: android cookies webview


    【解决方案1】:

    您可以在 CookieManager 实例上调用setCookie function,您可以通过在其上调用名为 getInstance 的静态方法来获取该实例。

    【讨论】:

    • 我将如何从服务器检索响应?
    • 哦,我误解了你的问题:实际上,最简单的事情可能是让 webview 自己提交表单。创建一个 webview,然后在其中启用 javascript。然后加载带有指向正确 url 的正确字段(已填写)的表单标签的 HTML 代码。然后装配一个 javascript onload 处理程序来提交表单。 webview可以自动处理cookies的存储。
    • 这看起来很简单,但我需要它完全自动化,并且用户不知道这个过程。有没有办法在后台做到这一点
    • 只需隐藏 WebView。
    【解决方案2】:

    一般来说,在Java HttpURLConnection 中你可以这样设置/获取cookie(这里是整个连接过程):

                HttpURLConnection conn = (HttpURLConnection) url.openConnection();             
    
                //set cookie. sCookie is my static cookie string
                if(sCookie!=null && sCookie.length()>0){
                    conn.setRequestProperty("Cookie", sCookie);                  
                }
    
                // Send data
                OutputStream os = conn.getOutputStream(); 
                os.write(mData.getBytes());
                os.flush();
                os.close(); 
    
                // Get the response!
                int httpResponseCode = conn.getResponseCode();         
                if (httpResponseCode != HttpURLConnection.HTTP_OK){
                   throw new Exception("HTTP response code: "+httpResponseCode); 
                }
    
                // Get the data and pass them to the XML parser
                InputStream inputStream = conn.getInputStream();                
                Xml.parse(inputStream, Xml.Encoding.UTF_8, mSaxHandler);                
                inputStream.close();
    
                //Get the cookie
                String cookie = conn.getHeaderField("set-cookie");
                if(cookie!=null && cookie.length()>0){
                    sCookie = cookie;              
                }
    
                /*   many cookies handling:                  
                String responseHeaderName = null;
                for (int i=1; (responseHeaderName = conn.getHeaderFieldKey(i))!=null; i++) {
                    if (responseHeaderName.equals("Set-Cookie")) {                  
                    String cookie = conn.getHeaderField(i);   
                    }
                }*/                
    
                conn.disconnect();                
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-30
      • 2016-01-09
      • 1970-01-01
      • 1970-01-01
      • 2014-02-26
      • 1970-01-01
      • 2016-04-29
      相关资源
      最近更新 更多