我希望我的Android应用程序能够向我的Django服务器发送一些信息。因此,我让Android应用程序将一个POST请求发送到mysite/upload页面,Django的视图将根据POST数据进行处理。问题是,服务器针对POST请求给出的响应抱怨CSRF验证失败。调查这个问题,似乎我可能需要先从服务器获取一个CSRF令牌,然后使用该令牌进行POST。但我不确定如何做到这一点。编辑:我已经发现可以使用视图装饰器@csrf_exempt关闭此视图的CSRF验证,但我不确定这是否是最佳解决方案。我的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);
这是我的视图处理上传的代码:
# 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