安卓发送POST请求Django的服务器CSRF失败 [英] Android sending post requests to django server csrf failing

查看:886
本文介绍了安卓发送POST请求Django的服务器CSRF失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我的Andr​​oid应用程序,以便能够发送一些信息给我的Django的服务器。所以,我提出的Andr​​oid应用程序发送POST请求的mysite /上传页面和Django的看法本页立足岗位数据会做的工作。问题是服务器给出了post请求抱怨CSRF verication失败的响应。展望的问题,看来我可能需要从服务器获取一个CSRF令牌第然后做后期与令牌,但我不能确定我是如何做到这一点。编辑:我发现我可以收工CRSF验证了使用视图修饰@csrf_exempt这个观点,但我不知道这是否是最佳的解决方案。我的Andr​​oid code:

  //创建一个新的HttpClient和门柱头球
                    HttpClient的HttpClient的=新DefaultHttpClient();
                    HttpPost httppost =新HttpPost(URL);

                    //添加数据
                    名单<的NameValuePair> namevaluepairs中=新的ArrayList<的NameValuePair>(2);
                    nameValuePairs.add(新BasicNameValuePair(scoreone,scoreone));
                    nameValuePairs.add(新BasicNameValuePair(scoretwo,scoretwo));
                    httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));
                    的System.out.println(huzahhhhhhh);
                    //执行HTTP POST请求
                    HTT presponse响应= httpclient.execute(httppost);
                    的BufferedReader在=新的BufferedReader(新的InputStreamReader(response.getEntity()的getContent()));
                    StringBuffer的SB =新的StringBuffer();
                    串线=;
                    串NL = System.getProperty(line.separator);
                    而((行= in.readLine())!= NULL){
                        sb.append(行+ NL);
                    }
                    附寄();
                    字符串结果= sb.toString();
                    的System.out.println(结果:+结果);
 

和我的看法code处理上传:

 #上传一个玩家匹配
高清上传(要求):
    如果request.method =='POST':
        scoreone = INT(request.POST ['scoreone'])
        scoretwo = INT(request.POST ['scoretwo'])
        M = Match.objects.create()
        MatchParticipant.objects.create(球员= Player.objects.get(PK = 1),匹配= M,得分= scoreone)
        MatchParticipant.objects.create(球员= Player.objects.get(PK = 2),匹配= M,得分= scoretwo)
    返回的Htt presponse(匹配上载)

在这里输入code
 

解决方案

写自己的装饰和添加一些秘密的头你的要求。的https://$c$c.djangoproject.com/browser/django/trunk/django/views/decorators/csrf.py

 高清csrf_exempt(view_func):
        
        标记视图功能是免征CSRF视图保护。
        
        #我们可以只是view_func.csrf_exempt = TRUE,但装饰
        #是,如果他们没有副作用更好,所以我们返回一个新的
        # 功能。
        高清wrapped_view(要求*的args,** kwargs):
            返回view_func(要求*的args,** kwargs)
            如果request.META.has_key('HTTP_X_SKIP_CSRF'):
                wrapped_view.csrf_exempt = TRUE
        返回包装(view_func,分配= available_attrs(view_func))(wrapped_view)
 

I would like my android app to be able to send some information to my django server. So I made the android app send a post request to the mysite/upload page and django's view for this page would do work based on the post data. The problem is the response the server gives for the post request complains about csrf verication failed. Looking in to the problem it seems I might have to get a csrf token from the server first then do the post with that token But I am unsure how I do this. Edit: I have found out that I can knock off the crsf verification for this view using a view decorator @csrf_exempt but I am not sure if this is the best solution. My android code:

// 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);

and my views code for handling the upload:

# 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

解决方案

Write own decorator and add some "secret" header to your request. 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, *args, **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)

这篇关于安卓发送POST请求Django的服务器CSRF失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆