我想我的android应用程序能够发送一些信息到我的django服务器。所以我让android应用程序向mysite/upload页面发送了一个post请求,而django对这个页面的看法会根据post数据做一些工作。问题是服务器对post请求的回应抱怨csrf验证失败。寻找这个问题,似乎我可能必须先从服务器获取csrf令牌,然后使用该令牌进行发布但我不确定我是如何做到这一点的。编辑:我已经发现,我可以使用视图装饰器@csrf_exempt剔除此视图的crsf验证,但我不确定这是否是最佳解决方案。我的Android代码:Android发送请求到Django服务器csrf失败
// 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);
和处理上传我的看法代码:
# 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
我得到403错误,我做同样的事情。 如果你已经解决了错误,你能帮助我吗? – 2014-06-19 11:41:12