维护HttpUrlConnection调用之间的会话(本机/ Webview) [英] Maintain session between HttpUrlConnection Calls (Native/Webview)

查看:121
本文介绍了维护HttpUrlConnection调用之间的会话(本机/ Webview)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我先从渴望开始:

我想创建一个部分原生的应用程序部分webviews

问题 - 维护本机和webview部分之间的会话。

Problem - Maintain a session between native and webview parts.

我的处理方法

我打算实施原生登录,我向用户提供了两个EditTextbox和一个按钮,用户输入凭据,我将它们作为JSON发布到服务器。

I intend to implement a native login, in which I present the user with two EditTextboxes and a button, the user enters credentials and I post them as JSON to the server.

服务器响应成功或错误。基于Success标志,我读取此连接的标头值并解压缩SessionCookie:

The Server responds with success or false. Based on Success flag I read the header values for this connection and extract the SessionCookie:

switch (responseCode) {
                case 200:

                    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    String inputLine;
                    response = new StringBuffer();
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();

                   //IF SUCCESS

                    Map<String, List<String>> map = conn.getHeaderFields();

                    for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                        System.out.println("Key : " + entry.getKey() + " ,Value : " + entry.getValue());
                    }

                    SSID = map.get("Set-Cookie").toString();
                    SSID = SSID.substring(1,SSID.length()-1);
                    return response.toString();
            }

,如下所示:

Set-Cookie ,Value : [PHPSESSID=e407ef64abb71b1ea2b8e4b30db76cf0; path=/, ci_session=a%3A0%3A%7B%7D; expires=Thu, 06-Nov-2014 16:54:57 GMT; Max-Age=-31500000; path=/, ci_session=a%3A5%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%22caedca696344458e7aa1b4ad02b3cfa0%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A13%3A%22182.59.130.42%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A60%3A%22Dalvik%2F2.1.0+%28Linux%3B+U%3B+Android+5.1.1%3B+Nexus+5+Build%2FLMY48B%29%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1446792897%3Bs%3A9%3A%22user_data%22%3Bs%3A0%3A%22%22%3B%7D5f4013e4a2edd2eb891ec8a2b8e8716e; expires=Sun, 05-Nov-2017 06:54:57 GMT; Max-Age=63072000; path=/, ci_session=a%3A4%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%22caedca696344458e7aa1b4ad02b3cfa0%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A13%3A%22182.59.130.42%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A60%3A%22Dalvik%2F2.1.0+%28Linux%3B+U%3B+Android+5.1.1%3B+Nexus+5+Build%2FLMY48B%29%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1446792897%3B%7Dc7eaa0945a7056db3cb9d336a02e5ecb; expires=Sun, 05-Nov-2017 06:54:57 GMT; Max-Age=63072000; path=/, ci_session=a%3A4%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%22caedca696344458e7aa1b4ad02b3cfa0%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A13%3A%22182.59.130.42%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A60%3A%22Dalvik%2F2.1.0+%28Linux%3B+U%3B+Android+5.1.1%3B+Nexus+5+Build%2FLMY48B%29%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1446792897%3B%7Dc7eaa0945a7056db3cb9d336a02e5ecb; expires=Sun, 05-Nov-2017 06:54:57 GMT; Max-Age=63072000; path=/]

警告:在上面 expires =星期四,06-Nov-2014 16:54:57 GMT

现在我想转到webview并添加此cookie标题,我正在做的事情:

Now I want to go to a webview and add this cookie to the header, which I am doing like:

Map<String, String> abc = new HashMap<String, String>();
            abc.put("Cookie", UniversalHttpUrlConnection.SSID);
            webView.loadUrl("https://someUrl/show_all", abc);

上述不起作用

我尝试了一种不同的方法,只是从上面的webview网址中读取 HTML

I tried a different approach, just to read the HTML from the above webview URL:

 public static String doHttpUrlConnectionAction(String desiredUrl, String headerValue)
            throws Exception {
        URL url = null;
        BufferedReader reader = null;
        StringBuilder stringBuilder;

        try {

            url = new URL(desiredUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Cookie", headerValue);

            connection.setRequestMethod("GET");

            connection.setDoOutput(true);


            connection.setReadTimeout(15 * 1000);
            connection.connect();


            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            stringBuilder = new StringBuilder();

            String line = null;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line + "\n");
            }
            return stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {

            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }

    }

我得到的HTML是Login页面,它本质上是一个重定向 - 因为服务器无法识别会话并重定向我。我在这里想念的是什么?我该如何继续会议?

The HTML I get is that of the Login page, which is essentially a redirect - as the server does not recognize the session and redirects me. What am I missing here? How can I continue the session?

编辑 - 进一步调试:

Edit - further debugging:

使用弃用:

HttpClient httpClient = new DefaultHttpClient(); //

我得到这些标题:

Key : Date ,Value : Sat, 07 Nov 2015 08:22:28 GMT
11-07 13:52:26.567 5264-5291/projects.test.com.webviewtest I/System.out: Key : Server ,Value : Apache/2.2.26 (Unix) mod_ssl/2.2.26 OpenSSL/0.9.8e-fips-rhel5 mod_bwlimited/1.4
11-07 13:52:26.567 5264-5291/projects.test.com.webviewtest I/System.out: Key : Set-Cookie ,Value : PHPSESSID=f27454f855fc5d5b2efa478537725992; path=/
11-07 13:52:26.567 5264-5291/projects.test.com.webviewtest I/System.out: Key : Expires ,Value : Thu, 19 Nov 1981 08:52:00 GMT
11-07 13:52:26.567 5264-5291/projects.test.com.webviewtest I/System.out: Key : Cache-Control ,Value : no-store, no-cache, must-revalidate, post-check=0, pre-check=0
11-07 13:52:26.567 5264-5291/projects.test.com.webviewtest I/System.out: Key : Pragma ,Value : no-cache
11-07 13:52:26.567 5264-5291/projects.test.com.webviewtest I/System.out: Key : Set-Cookie ,Value : ci_session=a%3A0%3A%7B%7D; expires=Fri, 07-Nov-2014 18:22:28 GMT; Max-Age=-31500000; path=/
11-07 13:52:26.567 5264-5291/projects.test.com.webviewtest I/System.out: Key : Set-Cookie ,Value : ci_session=a%3A5%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%2221d4f88af57e9c7477f48e0695bdb979%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A13%3A%22182.59.216.32%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A40%3A%22Apache-HttpClient%2FUNAVAILABLE+%28java+1.4%29%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1446884548%3Bs%3A9%3A%22user_data%22%3Bs%3A0%3A%22%22%3B%7D58938a4e97b08c01faa7fec0025bdc49; expires=Mon, 06-Nov-2017 08:22:28 GMT; Max-Age=63072000; path=/
11-07 13:52:26.567 5264-5291/projects.test.com.webviewtest I/System.out: Key : Set-Cookie ,Value : ci_session=a%3A4%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%2221d4f88af57e9c7477f48e0695bdb979%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A13%3A%22182.59.216.32%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A40%3A%22Apache-HttpClient%2FUNAVAILABLE+%28java+1.4%29%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1446884548%3B%7D30e2cc6561b3fb9659c7809d0c82946d; expires=Mon, 06-Nov-2017 08:22:28 GMT; Max-Age=63072000; path=/
11-07 13:52:26.567 5264-5291/projects.test.com.webviewtest I/System.out: Key : Set-Cookie ,Value : ci_session=a%3A4%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%2221d4f88af57e9c7477f48e0695bdb979%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A13%3A%22182.59.216.32%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A40%3A%22Apache-HttpClient%2FUNAVAILABLE+%28java+1.4%29%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1446884548%3B%7D30e2cc6561b3fb9659c7809d0c82946d; expires=Mon, 06-Nov-2017 08:22:28 GMT; Max-Age=63072000; path=/
11-07 13:52:26.567 5264-5291/projects.test.com.webviewtest I/System.out: Key : Vary ,Value : Accept-Encoding
11-07 13:52:26.567 5264-5291/projects.test.com.webviewtest I/System.out: Key : Content-Length ,Value : 95
11-07 13:52:26.567 5264-5291/projects.test.com.webviewtest I/System.out: Key : Connection ,Value : close
11-07 13:52:26.567 5264-5291/projects.test.com.webviewtest I/System.out: Key : Content-Type ,Value : text/html

开头警告

Invalid cookie header: "Set-Cookie: ci_session=a%3A0%3A%7B%7D; expires=Fri, 07-Nov-2014 18:22:28 GMT; Max-Age=-31500000; path=/". Negative max-age attribute: -31500000

观察
设置-Cookie来了4次,第一次造成异常。

Observation Set-Cookie is coming 4 times, the first one causing an exception.

现在使用HttpUrlConnection:

Now using a HttpUrlConnection:

HttpURLConnection conn = null;
conn = (HttpURLConnection) url.openConnection();

以下是我得到的标题:

 Key : null ,Value : [HTTP/1.1 200 OK]
11-07 13:52:27.646 5264-5291/projects.test.com.webviewtest I/System.out: Key : Cache-Control ,Value : [no-store, no-cache, must-revalidate, post-check=0, pre-check=0]
11-07 13:52:27.646 5264-5291/projects.test.com.webviewtest I/System.out: Key : Connection ,Value : [close]
11-07 13:52:27.646 5264-5291/projects.test.com.webviewtest I/System.out: Key : Content-Type ,Value : [text/html]
11-07 13:52:27.649 5264-5291/projects.test.com.webviewtest I/System.out: Key : Date ,Value : [Sat, 07 Nov 2015 08:22:29 GMT]
11-07 13:52:27.649 5264-5291/projects.test.com.webviewtest I/System.out: Key : Expires ,Value : [Thu, 19 Nov 1981 08:52:00 GMT]
11-07 13:52:27.649 5264-5291/projects.test.com.webviewtest I/System.out: Key : Pragma ,Value : [no-cache]
11-07 13:52:27.649 5264-5291/projects.test.com.webviewtest I/System.out: Key : Server ,Value : [Apache/2.2.26 (Unix) mod_ssl/2.2.26 OpenSSL/0.9.8e-fips-rhel5 mod_bwlimited/1.4]
11-07 13:52:27.650 5264-5291/projects.test.com.webviewtest I/System.out: Key : Set-Cookie ,Value : [PHPSESSID=9d98c8d97660664e550f19913783c089; path=/, ci_session=a%3A0%3A%7B%7D; expires=Fri, 07-Nov-2014 18:22:29 GMT; Max-Age=-31500000; path=/, ci_session=a%3A5%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%228cf5e634854030668573ec1f0dc9c6d9%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A13%3A%22182.59.216.32%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A60%3A%22Dalvik%2F2.1.0+%28Linux%3B+U%3B+Android+5.1.1%3B+Nexus+5+Build%2FLMY48B%29%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1446884549%3Bs%3A9%3A%22user_data%22%3Bs%3A0%3A%22%22%3B%7D9e233ffe356e965178da38e538fd8b31; expires=Mon, 06-Nov-2017 08:22:29 GMT; Max-Age=63072000; path=/, ci_session=a%3A4%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%228cf5e634854030668573ec1f0dc9c6d9%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A13%3A%22182.59.216.32%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A60%3A%22Dalvik%2F2.1.0+%28Linux%3B+U%3B+Android+5.1.1%3B+Nexus+5+Build%2FLMY48B%29%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1446884549%3B%7D53b1ee5e2e625d24d33a153a50881093; expires=Mon, 06-Nov-2017 08:22:29 GMT; Max-Age=63072000; path=/, ci_session=a%3A4%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%228cf5e634854030668573ec1f0dc9c6d9%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A13%3A%22182.59.216.32%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A60%3A%22Dalvik%2F2.1.0+%28Linux%3B+U%3B+Android+5.1.1%3B+Nexus+5+Build%2FLMY48B%29%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1446884549%3B%7D53b1ee5e2e625d24d33a153a50881093; expires=Mon, 06-Nov-2017 08:22:29 GMT; Max-Age=63072000; path=/]
11-07 13:52:27.651 5264-5291/projects.test.com.webviewtest I/System.out: Key : Vary ,Value : [Accept-Encoding]
11-07 13:52:27.651 5264-5291/projects.test.com.webviewtest I/System.out: Key : X-Android-Received-Millis ,Value : [1446884547643]
11-07 13:52:27.651 5264-5291/projects.test.com.webviewtest I/System.out: Key : X-Android-Response-Source ,Value : [NETWORK 200]
11-07 13:52:27.651 5264-5291/projects.test.com.webviewtest I/System.out: Key : X-Android-Sent-Millis ,Value : [1446884547076]

观察:
Set-Cookie打包在一起,共有四个实例。

Observation: Set-Cookie is packed together, four instances.

当我手动在 Advanced Rest Client 中尝试此操作时,一切正常。我得到了所需的HTML页面 - 经过身份验证。

When I try this in the Advanced Rest Client manually, everything works proper. I get the desired HTML page - authenticated.

观察:
高级休息客户应用只有当我在同一浏览器中登录网站时才会给出正确的结果。基本上,cookie被覆盖了。

Observation: The Advanced Rest Client App gives proper results only if I am logged into the website, in the same browser. So essentially the cookies are getting overridden.

观察

我厌倦了试图从中获取会话cookie HttpUrlConnection,我为更改所做的是加载webview并在其中登录。

I got fed up trying to get the session cookies from the HttpUrlConnection, what I did for a change is to load a webview and login inside of it.

其次我放了一个按钮来激活我的HttpUrlConnection - 并尝试访问需要身份验证的页面。

Second I put up a button which fires my HttpUrlConnection - and tries to access a page which requires authentication.

在这个HttpUrlConnection内部,我做了类似这样的事情:

Inside of this HttpUrlConnection I did something like this:

 CookieManager cookieManager = CookieManager.getInstance();
            String cookie = cookieManager.getCookie(new URL("https://urlinQuestion.com").getHost());
            System.out.println("Cookie from cookie store" + cookie);
            connection.setRequestProperty("Cookie", cookie);

所以我将我在webView中获得的cookie传递给HttpUrlCOnnection。有用。现在我的感觉是为了扭转事件的顺序(因为我希望cookie形成UrlConnection - 将它们传递给webview)我将不得不更新cookie管理器。 (New Voyage从这里开始)

So I pass the cookies which I get in the webView to the HttpUrlCOnnection. It works. Now what I feel is that inorder to reverse the order of events (As I want the cookies form UrlConnection - pass them to webview) I will have to update the cookie manager. (New Voyage starts here)

为了记录,我在下面添加两个cookie:
第一个不起作用,第二个我从webview获得方式和工作,我发现语义没有区别:

For record sake I am adding two cookies below: The first one does not work, the second one I get from the webview way and works, I find no difference in semantics though:

PHPSESSID=a3d2367f8a5a3221e9bad1a91a34fd55; ci_session=a%3A4%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%221381c152699fb61d04663c9b854ecdd7%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A14%3A%22182.59.245.196%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A60%3A%22Dalvik%2F2.1.0+%28Linux%3B+U%3B+Android+5.1.1%3B+Nexus+5+Build%2FLMY48B%29%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1447140920%3B%7Ddd2c014724b9ca061b50774f1fea235d


PHPSESSID=348345a2bf9f9733037915fd36a4ad6c; 
ci_session=a%3A4%3A%7Bs%3A10%3A%22
session_id%22%3Bs%3A32%3A%2209304f814a6ed6ad726dabca74b94182%22%3Bs%3A10%3A%22
ip_address%22%3Bs%3A14%3A%22182.59.202.107%22%3Bs%3A10%3A%22
user_agent%22%3Bs%3A60%3A%22Dalvik%2F2.1.0+%28Linux%3B+U%3B+Android+5.1.1%3B+Nexus+5+Build%2FLMY48B%29%22%3Bs%3A13%3A%22
last_activity%22%3Bi%3A1447127988%3B%7D18055bfdb2d59618a324aff37a58871d

使用上面要阅读的工具

推荐答案

我最接近的就是使用webview作为登录。然后,您可以在HttpUrlConnection中继续您的会话,并从webview获取cookie。 cookie可以按如下方式使用:

The closest I could get to this is, by using a webview as login. Then you can continue your session in the HttpUrlConnection, with the cookies fetched from webview. The cookies can be used as follows:

HttpURLConnection urlConnection = null;
try {
    urlConnection = (HttpURLConnection) url.openConnection();

    // Fetch and set cookies in requests
    CookieManager cookieManager = CookieManager.getInstance();
    String cookie = cookieManager.getCookie(urlConnection.getURL().toString());
    if (cookie != null) {
        urlConnection.setRequestProperty("Cookie", cookie);
    }
    urlConnection.connect();

    // Get cookies from responses and save into the cookie manager
    List cookieList = urlConnection.getHeaderFields().get("Set-Cookie");
    if (cookieList != null) {
        for (String cookieTemp : cookieList) {
            cookieManager.setCookie(urlConnection.getURL().toString(), cookieTemp);
        }
    }

    InputStream in = new BufferedInputStream (urlConnection.getInputStream());
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (urlConnection != null) {
        urlConnection.disconnect();
    }
}

这篇关于维护HttpUrlConnection调用之间的会话(本机/ Webview)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆