我有一个Android应用程序试图将用户注册到django服务器,用json发送POST请求。
我得到的响应代码是500 INTERNAL SERVER ERROR
Android代码:
httpClient = new DefaultHttpClient();
registerUserRequest = new HttpPost("http://10.100.102.9:8000/users/register");
public void registerUser(){
Map<String, String> userMap = new HashMap<String, String>();
userMap.put("username", "UserName");
userMap.put("password", "12345");
userMap.put("first_name", "first");
userMap.put("last_name", "last");
JSONObject obj=new JSONObject(params);
StringEntity se = new StringEntity(obj.toString());
registerUserRequest.setEntity(se);
registerUserRequest.setHeader("Content-type", "application/json");
new executeRequest().execute(registerUserRequest);
}
private class executeRequest extends AsyncTask<HttpRequest, Void, Integer>
{
@Override
protected Integer doInBackground(HttpRequest... params) {
// TODO Auto-generated method stub
HttpRequest request = params[0];
int responseCode = -1;
ResponseHandler responseHandler = new BasicResponseHandler();
HttpResponse response;
try {
response = httpClient.execute(registerUserRequest,
responseHandler);
Log.d("Response of REGISTER_USER request", response.toString());
responseCode = response.getStatusLine().getStatusCode();
} catch (ClientProtocolException e) {
// This exception raised
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return responseCode;
}
}
引发的异常是AsyncTask中的ClientProtocolException。
Django代码:
class UserViewSet(viewsets.ReadOnlyModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
@list_route(methods=['post'])
def register(self, request):
serializer = UserSerializer(data=request.DATA)
if serializer.is_valid():
user = User.objects.create_user(
username = serializer.init_data['username'],
password = serializer.init_data['password'],
first_name = serializer.init_data['first_name'],
last_name = serializer.init_data['last_name'],
)
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
网址很好我测试了 - “http://10.100.102.9:8000/users/register”
错误:我得到的响应代码是500 INTERNAL SERVER ERROR
05-24 13:05:14.317: W/System.err(15625): org.apache.http.client.HttpResponseException: INTERNAL SERVER ERROR
05-24 13:05:14.317: W/System.err(15625): at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:71)
05-24 13:05:14.327: W/System.err(15625): at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:59)
05-24 13:05:14.337: W/System.err(15625): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:657)
05-24 13:05:14.337: W/System.err(15625): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:627)
任何想法为什么会发生这种情况?
谢谢!
答案 0 :(得分:2)
500 INTERNAL SERVER ERROR表示服务器端代码中的错误,而不是移动端。 检查服务器端发生的异常。