【问题标题】:Android, how to get a cookie from URL via HttpClient()?Android,如何通过 HttpClient() 从 URL 获取 cookie?
【发布时间】:2014-08-08 13:15:26
【问题描述】:

我有一个登录活动,我必须为我的网站创建一个发布请求,以使用户登录到我的移动应用程序。要在我的网站上创建发布请求,我需要 csrf cookie 作为参数,这意味着我必须首先从我的 URL 获取 cookie,然后使用 csrf 值创建我的发布请求。

这是我的代码:

        HttpClient client = new DefaultHttpClient();

        HttpPost post = new HttpPost("http://192.168.178.163:8080/login/");

        try {

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
            nameValuePairs.add(new BasicNameValuePair("username", "xxx"));
            nameValuePairs.add(new BasicNameValuePair("password", "yyy"));
            //csrfmiddlewaretoken
            String res = null;

            post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = client.execute(post);
            res = response.toString();
            res = res.replaceAll("\\s+","");
            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            String line = "";
            while ((line = rd.readLine()) != null) {
                Log.i("line", line);
                //System.out.println(line);
                if (line.startsWith("csrftoken=")) {
                    String key = line.substring(5);
                    Log.i("key", key);
                }

            }
        }
        catch (IOException e) {
            txt_Error.setText(e.toString());
        }

知道怎么做吗?我已经阅读过关于 CookieSyncManager 的内容,但我根本不明白......任何想法或代码示例都会很受欢迎

【问题讨论】:

  • 如果接收到的页面,cookies 在标头中。您是否搜索过该网站以提取这些 cookie?按下cookies按钮,你会发现。
  • 这正是我需要的,我没有找到:(
  • 看到这个帖子,希望对你有帮助:stackoverflow.com/questions/11100086/…

标签: java android cookies android-cookiemanager


【解决方案1】:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://192.168.178.163:8080/login/");
CookieStore cookieStore = new BasicCookieStore();
HttpContext context = new BasicHttpContext();
context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
...
HttpResponse response = client.execute(post, context);
List<Cookie> cookies = cookieStore.getCookies();
CookieMonster.eat(cookies); // :)

【讨论】:

  • 嗨!谢谢你的回答,吃饼干的部分很有趣哈哈哈...... :D......还有一个问题,我必须从我的上下文中提取cookie并将其作为参数传递给用户名和密码,知道吗? :)
  • 由于使用了csrf,你可能需要先做一个get请求来获取token和cookie数据,然后在post请求中使用。
【解决方案2】:

首先是获取 csrftoken,(正如您在问题中提到的那样)。 AFAIK,您还必须将 csrftoken 作为数据发布到发布请求中,后端将检查/匹配 cookie 和发布数据。

例如,对于 django 后端,您必须添加如下内容:

nameValuePairs.add(new BasicNameValuePair("csrfmiddlewaretoken", "OBTAINED_TOKEN"));

如果来自http://192.168.178.163:8080/login/ 的获取请求返回一个表单,您可以检查源,它可能包含一个隐藏字段,其中包含您需要发送的令牌的名称/值。

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2012-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-02
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多