【发布时间】:2015-03-07 06:53:39
【问题描述】:
我为 django rest 框架编写 android 客户端。我将 ModelsViewSet 与 django rest 框架一起使用。当我尝试使用我的 android 客户端创建新用户时,我收到此错误:
[08/Jan/2015 22:49:23]“POST /users/HTTP/1.1”403 59
这是我的安卓客户端代码:
public class Test extends Activity {
String URL = "http://192.168.0.103:8000/users/";
String result = "";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_layout);
/*
*Make http call to the webservice
*/
RequestTask ws = new RequestTask();
ws.execute(URL);
} // end onCreate()
private class RequestTask extends AsyncTask<String, String, String>{
@Override
protected String doInBackground(String... uri) {
// TODO Auto-generated method stub
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
HttpPost httppost = new HttpPost(uri[0]);
try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", "dinho"));
nameValuePairs.add(new BasicNameValuePair("date_of_birth", "2013-12-11"));
nameValuePairs.add(new BasicNameValuePair("gender", "Male"));
nameValuePairs.add(new BasicNameValuePair("description", "tout choco"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpClient.execute(httppost);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
}else{
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
}catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return responseString;
}
@Override
protected void onPostExecute(String result) {
if (result!=null) {
EditText et = (EditText)findViewById(R.id.ws_test_field);
et.setText(result);
}
}
}
}
这是我的模型视图集
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly, permissions.AllowAny)
请帮助我,我从 2 天开始就尝试解决此步骤。感谢您的帮助。
【问题讨论】:
-
@aschattney 你认为这是 csrf_token 的问题吗?
-
有什么方法可以获得正在返回的 403 响应的正文?这就是它会告诉你问题所在的地方。
-
@KevinBrown 没有任何方法可以获得 403 响应的正文,但我现在是身份验证或权限错误,但我不知道如何解决它
-
是的,我认为您需要提供令牌作为参数或完全禁用此中间件..
标签: android python django django-rest-framework