我有一个登录活动,我必须为我的网站创建一个发布请求,以将用户登录到我的移动应用程序。要在我的网站上创建发布请求,我需要 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 但我根本不明白......任何想法或代码示例都会很受欢迎