【发布时间】:2015-07-14 10:07:49
【问题描述】:
我在这里和其他网页尝试并搜索了很多答案,但我花了一整天时间仍然无法做到。
一个朋友构建了一个 django 后端,他让我构建一个 android 应用程序来连接到该后端,最好的结果是这个 Android Client login to a Django server, how to pass crsf :| 但我无法让它工作,我从服务器获取 CSRF 但是然后我尝试使用 URLConnection、HttpClient、HttpPost,还有很多其他示例,但什么都没有。
现在我的代码是:
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://URL-TO-SERVER/");
String CSRFTOKEN = getCsrfFromUrl("http://URL-TO-SERVER/");
// Add your data
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", mEmail));
nameValuePairs.add(new BasicNameValuePair("password", mPassword));
nameValuePairs.add(new BasicNameValuePair("csrfmiddlewaretoken", CSRFTOKEN));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httppost.setHeader("X-CSRFToken", CSRFTOKEN);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
final BasicCookieStore cookieStore = new BasicCookieStore();
BasicClientCookie csrf_cookie = new BasicClientCookie("X-CSRFToken", CSRFTOKEN);
csrf_cookie.setDomain("URL-SERVER");
cookieStore.addCookie(csrf_cookie);
// Create local HTTP context - to store cookies
HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
// Execute HTTP Post Request
HttpResponse response = null;
try {
Log.e(TAG,"Token: "+CSRFTOKEN);
response = httpclient.execute(httppost, localContext);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(response.getAllHeaders());
try {
System.out.println(EntityUtils.toString(response.getEntity()));
} catch (IOException e) {
e.printStackTrace();
}
并且 getCsrfFromUrl() 来自链接。而在
nameValuePairs.add(new BasicNameValuePair("csrfmiddlewaretoken", CSRFTOKEN));
我尝试更改 x-CSRFToken 的 csrftoken 的密钥,但我仍然不知道出了什么问题或如何让它工作,也许是后端有问题?缺少功能或键? 我尝试做的是登录一个需要输入用户名和密码的页面,然后重新收集响应以查看谁输入并使用了该数据。
【问题讨论】:
-
另一个问题中的
getCsrfFromUrl函数不起作用。