当前位置:  开发笔记 > 编程语言 > 正文

在Android上使用BasicHttpRequest从webview共享cookie

如何解决《在Android上使用BasicHttpRequest从webview共享cookie》经验,为你挑选了0个好方法。

我发送cookie作为http get的一部分时遇到问题.首先,我进入webview中的登录页面,它给了我一个cookie.我检查过,cookie存储在CookieManager中.然后我使用BasicHttpRequest从同一个域获取特定的URL.我希望我从登录中获得的cookie可以附加到我的头文件中获取,但是在Wireshark中查看它并不存在.我用Google搜索并阅读了很多类似的问题,并确保:

我正在使用CookieSyncManager,所以我希望会话中的cookie会持续存在.我不认为CookieSyncManager是异步的是一个问题,因为我每隔5秒就会点击一次URL,而且永远不会添加cookie.

我怀疑我需要告诉我关于我的cookie商店的http请求,但我用Google搜索的解决方案不能为我编译.看起来我想做一些看起来像context.setAttribute(ClientContext.COOKIE_STORE,this.cookieStore)的东西,但我无法弄清楚如何从CookieManager中获取默认的CookieStore.有些代码似乎调用了cookieManager.getCookieStore()但是在Android上没有为我编译.看看文档,我看不到找到疯狂的CookieStore的方法 - 我错过了一些明显的东西吗?

我在webview中启动登录页面的代码如下所示:

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

然后我检查cookie的代码看起来像:

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

而实际上我做的http请求

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

感谢您阅读这篇文章!感激地收到任何建议,

艾米

推荐阅读
N个小灰流_701
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有