gpt4 book ai didi

Android向django服务器csrf发送post请求失败

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:01:36 26 4
gpt4 key购买 nike

我希望我的 android 应用程序能够将一些信息发送到我的 django 服务器。所以我让 android 应用程序向 mysite/upload 页面发送一个发布请求,django 对该页面的 View 将根据发布数据工作。问题是服务器对 post 请求的响应提示 csrf 验证失败。查看问题似乎我可能必须先从服务器获取 csrf token 然后使用该 token 进行发布但我不确定我是如何做到这一点的。编辑:我发现我可以使用 View 装饰器@csrf_exempt 取消此 View 的 crsf 验证,但我不确定这是否是最佳解决方案。我的安卓代码:

// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);

// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("scoreone", scoreone));
nameValuePairs.add(new BasicNameValuePair("scoretwo", scoretwo));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
System.out.println("huzahhhhhhh");
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
System.out.println("Result: "+result);

和我处理上传的 View 代码:

# uploads a players match
def upload(request):
if request.method == 'POST':
scoreone = int(request.POST['scoreone'])
scoretwo = int(request.POST['scoretwo'])
m = Match.objects.create()
MatchParticipant.objects.create(player = Player.objects.get(pk=1), match = m, score = scoreone)
MatchParticipant.objects.create(player = Player.objects.get(pk=2), match = m, score = scoretwo)
return HttpResponse("Match uploaded" )

enter code here

最佳答案

首先,您需要从预览请求的 cookie 中读取 csrf token :

httpClient.execute(new HttpGet(uri));
CookieStore cookieStore = httpClient.getCookieStore();
List <Cookie> cookies = cookieStore.getCookies();
for (Cookie cookie: cookies) {
if (cookie.getDomain().equals(Constants.CSRF_COOKIE_DOMAIN) && cookie.getName().equals("csrftoken")) {
CSRFTOKEN = cookie.getValue();
}
}

If your view is not rendering a template containing the csrf_token template tag, Django might not set the CSRF token cookie. This is common in cases where forms are dynamically added to the page. To address this case, Django provides a view decorator which forces setting of the cookie: ensure_csrf_cookie(). -- https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

然后在做post请求的时候可以在post请求头和cookies上传递给服务器:

httpPost.setHeader("Referer", Constants.SITE_URL);
httpPost.setHeader("X-CSRFToken", CSRFTOKEN);

DefaultHttpClient client = new DefaultHttpClient();
final BasicCookieStore cookieStore = new BasicCookieStore();

BasicClientCookie csrf_cookie = new BasicClientCookie("csrftoken", CSRFTOKEN);
csrf_cookie.setDomain(Constants.CSRF_COOKIE_DOMAIN);
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);

HttpResponse response = client.execute(httpPost, localContext);

关于Android向django服务器csrf发送post请求失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9252360/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com