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):
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
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(); } }
add following post request:
urlconnection.setrequestproperty("x-csrftoken", csrftoken); urlconnection.setrequestproperty("cookie", cookiestring);
Comments
Post a Comment