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

前端之家收集整理的这篇文章主要介绍了Android发送发送请求到django服务器csrf失败前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想我的 Android应用程序能够发送一些信息到我的django服务器.所以我做的Android应用程序发送一个发布请求到mysite /上传页面,django的这个页面的视图将基于post数据工作.问题是服务器对post请求的响应,关于csrf验证失败.看看这个问题,似乎我可能必须先从服务器获取一个csrf令牌,然后用该令牌做帖子但是我不知道我该怎么做.编辑:我已经发现,我可以使用视图装饰器@csrf_exempt敲击crsf验证这个视图,但我不知道这是否是最好的解决方案.我的Android代码
// 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);
@H_403_4@和我的视图代码来处理上传

# 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),score = scoretwo)
    return HttpResponse("Match uploaded" )

enter code here

解决方法

编写自己的装饰器,并在您的请求中添加一些“秘密”标题. https://code.djangoproject.com/browser/django/trunk/django/views/decorators/csrf.py
def csrf_exempt(view_func):
        """
        Marks a view function as being exempt from the CSRF view protection.
        """
        # We could just do view_func.csrf_exempt = True,but decorators
        # are nicer if they don't have side-effects,so we return a new
        # function.
        def wrapped_view(request,*args,**kwargs):
            return view_func(request,**kwargs)
            if request.Meta.has_key('HTTP_X_SKIP_CSRF'):
                wrapped_view.csrf_exempt = True
        return wraps(view_func,assigned=available_attrs(view_func))(wrapped_view)
原文链接:https://www.f2er.com/android/312861.html

猜你在找的Android相关文章