我想我的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