我正在构建一个应用程序,我提示用户注册。我有一个 django-restful 服务器在后端运行,我试图通过 DefaultHttpClient 类在Android客户端上向我的服务器发出HTTP post请求。我从用户那里获得了电子邮件,用户名等,并且在按钮的onClick事件中,我创建了一个 AsnycTask 来执行请求。以下是活动的代码:
registerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
String userName = usernameEditText.getText().toString();
String email = emailEditText.getText().toString();
String password = passwordEditText.getText().toString();
if( userName != null && email != null && password != null) {
new RegisterEventHandler().execute(userName , email , password);
}
}
});
....
class RegisterEventHandler extends AsyncTask<String, Integer, Boolean> {
@Override
protected Boolean doInBackground(String... params) {
RequestHandler handler = new RequestHandler();
return handler.register(params[0], params[1], params[2]);
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if( result ) {
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setTitle(R.string.RegisterSuccessfullTitle);
builder.setMessage(R.string.RegisterSuccessfullMessage);
builder.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent redirect = new Intent(getApplicationContext() , SmartMapMainActivity.class);
startActivity(redirect);
}
});
builder.create().show();
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setTitle(R.string.RegisterFailedTitle);
builder.setMessage(R.string.RegisterFailedMessage);
builder.create().show();
}
}
}
RequestHandler类:
public class RequestHandler {
public boolean register(String userName , String email , String password) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://127.0.0.1/users/");
try {
JSONObject jsonObj = new JSONObject();
jsonObj.put("username", userName);
jsonObj.put("email", email);
jsonObj.put("password", password);
StringEntity entity = new StringEntity(jsonObj.toString());
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
if(response.getStatusLine().getStatusCode() == 200)
return true;
else
return false;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
}
问题是, DefaultHttpClient 的connManager(ClientConnectionManager)始终是 null ,并且在 execute()方法中 HttpClient ,它总是抛出 IOException 。我尝试在我的活动中初始化 DefaultHttpClient ,而不是在AsyncTask的 doInBackground 方法中,但结果是相同的。