我正在开发一个 android 应用程序,该应用程序将 JSON 对象发布到服务器并得到一个响应。我被困在如何让服务器响应的 JSON 返回主线程。下面是我到目前为止的代码。即使在我运行后台进程之后,当我调用 getResponse 时它也会返回 null。
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.os.AsyncTask;
public class AsyncHttpPost extends AsyncTask<String, String, HttpResponse> {
private JSONObject mData = null;// post data
private HttpResponse response = null;
/**
* constructor
*/
public AsyncHttpPost(JSONObject json) {
mData = json;
}
public HttpResponse getResponse() {
return response;
}
/**
* background
*/
@Override
protected HttpResponse doInBackground(String... params) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(params[0]);
try {
post.setEntity(new StringEntity(mData.toString()));
response = client.execute(post);
}catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (Exception e) {
}
return response;
}
}