Android Calling Django Server With POST Data -


someone may asked question cannot find suggestions.

i writing android app needs access django server using httpsurlconnection django server return json array android.

the view function in django receive parameters request.post , generate json array return using httpresponse django method. not need templates , forms.

when call django view function android, returns 403 error. know because post data not contains "csrf_token".

my problem is: how can "csrf_token" , put post data before send django? try disable csrf checking "@csrf_exempt" can return correct result android app not disable csrf checking.

thanks, wilson

you have send cookies , have send header 'x-csrftoken' csrftoken.

this (may not best way):

  1. get csrf token via request.but first try see if csrftoken cookie doing same request on browser developer tools. if not, should use ensure_csrf_cookie decorator

    from django.views.decorators.csrf import ensure_csrf_cookie @ensure_csrf_cookie def your_view(request):     pass 
  2. now using same httpurlconnection object :

    string cookiestring=""; string csrftoken="";  // below code can shortened using for-each loop list<httpcookie> cookies=cookiemanager.getcookiestore().getcookies(); iterator<httpcookie> cookieiterator=cookies.iterator(); while(cookieiterator.hasnext()){     httpcookie cookie=cookieiterator.next();     cookiestring+=cookie.getname()+"="+cookie.getvalue()+";";     if(cookie.getname().equals("csrftoken")){         csrftoken=cookie.getvalue();     } } 
  3. add following post request:

    urlconnection.setrequestproperty("x-csrftoken", csrftoken); urlconnection.setrequestproperty("cookie", cookiestring); 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -