在 Android 中将 cookie 设置为 webView [英] Set a cookie to a webView in Android

查看:37
本文介绍了在 Android 中将 cookie 设置为 webView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在检查用户名或密码是否正确时,我从服务器获取 HttpResponse.当我在 webview 中加载 url 时,我希望 webView 拥有 cookie(我用 postData() 存储在 webView 中.我希望 webView 获取 cookie 并使用存储在 webview 中的 cookie 加载 url.

I'm getting a HttpResponse from a server when checking if a username or password is correct. When I load the url in a webview I want the webView to have the cookie (the answer I get with postData() stored in the webView. I want the webView to pickup the cookie and load the url with that cookie stored in the webview.

我正在收到回复.

public HttpResponse postData() {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("https://example.com/login.aspx");

    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("txtUsername", "user"));
        nameValuePairs.add(new BasicNameValuePair("txtPassword", "123"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = httpclient.execute(httppost);
        String responseAsText = EntityUtils.toString(response.getEntity());
        Log.v(TAG , "Response from req: " + responseAsText);
        return responseAsText;

    } catch (ClientProtocolException e) {

    } catch (IOException e) {

    }
    return null;
}

我用:

webView.loadUrl("http://a_page.com/getpage.aspx?p=home");

我想我并没有真正管理 cookie,我也不知道该怎么做.有什么建议或解决方案吗?

I guess I'm not really managing a cookie and I have no idea how to do so. Any suggestions or solutions?

推荐答案

其实很简单.

String cookieString = "cookie_name=cookie_value; path=/";
CookieManager.getInstance().setCookie(baseUrl, cookieString);

其中 cookieString 的格式与更传统的 Set-Cookie HTTP 标头相同,baseUrl 是 cookie 应属于的站点.

where cookieString is formatted the same as a more traditional Set-Cookie HTTP header, and baseUrl is the site the cookie should belong to.

这篇关于在 Android 中将 cookie 设置为 webView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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