Android,如何通过HttpClient()从URL获取cookie?
我有登录活动,我必须为我的网站创建一个post请求,以便将用户登录到我的移动应用程序中。 要在我的网站上创建post请求,我需要将csrf cookie作为参数,这意味着我首先从我的URL获取cookie并在创建带有csrf值的post请求之后。
这是我的代码:
HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://192.168.178.163:8080/login/"); try { List nameValuePairs = new ArrayList(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的内容,但我根本不理解……任何想法或代码示例都会非常容易
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 cookies = cookieStore.getCookies(); CookieMonster.eat(cookies); // :)
首先要获得csrftoken,(正如你在问题中提到的那样)。 AFAIK你还必须在后期请求中将csrftoken作为数据发布,后端将检查/匹配cookie和发布数据。
例如,对于django后端,您必须添加以下内容:
nameValuePairs.add(new BasicNameValuePair("csrfmiddlewaretoken", "OBTAINED_TOKEN"));
如果来自http://192.168.178.163:8080/login/
的get请求返回一个表单,您可以检查源,它可能包含一个隐藏字段,其中包含您需要发送的令牌的名称/值。
- 所以基本上创建一个
http://192.168.178.163:8080/login/
的获取请求 - 将Cookie解压缩为字符串
- 使用https://stackoverflow.com/a/15924948/1714030复制cookie
- 创建您的发布请求
希望这可以帮助