【发布时间】:2012-02-12 20:25:22
【问题描述】:
我希望我的 android 应用能够向我的 django 服务器发送一些信息。所以我让 android 应用程序向 mysite/upload 页面发送一个发布请求,并且 django 对该页面的视图将根据发布数据工作。问题是服务器对发布请求的响应抱怨 csrf 验证失败。调查这个问题似乎我可能必须先从服务器获取一个 csrf 令牌,然后使用该令牌进行发布但我不确定我是如何做到这一点的。编辑:我发现我可以使用视图装饰器 @csrf_exempt 取消此视图的 crsf 验证,但我不确定这是否是最佳解决方案。我的安卓代码:
// 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 错误,我也在做同样的事情。如果你解决了错误,你能帮我吗?
标签: android django post request