【发布时间】:2019-03-30 14:37:36
【问题描述】:
我正在尝试从我的 andorid 应用程序中的 HTTP 发布请求中获取 json string。使用来自this post 的解决方案,此处也显示了代码。
public void post(String completeUrl, String body) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(completeUrl);
httpPost.setHeader("Content-type", "application/json");
try {
StringEntity stringEntity = new StringEntity(body);
httpPost.getRequestLine();
httpPost.setEntity(stringEntity);
httpClient.execute(httpPost);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
我从异步任务内部调用 post(用于在单独的线程上处理网络访问)。
String result;
result = post("https://StringURLGoesHere.com/", "jsonStringBodyGoesHere");
根据documentation for HttpClient class,要处理响应,我需要在 HttpClient.execute() 方法中添加第二个参数 ResponseHandler。
public interface ResponseHandler<T> {
T handleResponse(HttpResponse var1) throws ClientProtocolException, IOException;
}
我就是这样做的:
public String post(String completeUrl, String body) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(completeUrl);
httpPost.setHeader("Content-type", "application/json");
try {
StringEntity stringEntity = new StringEntity(body);
httpPost.getRequestLine();
httpPost.setEntity(stringEntity);
ResponseHandler<String> reply = new ResponseHandler<String>() {
@Override
public String handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {
return httpResponse.toString();
}
};
return httpClient.execute(httpPost,reply);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
我在我的应用程序的文本视图中显示字符串。上面写着:
org.apache.http.message.BasicHttpResponse@1446ef0c
或
org.apache.http.message.BasicHttpResponse@b83bd3d
或
org.apache.http.message.BasicHttpResponse@1c4c9e1d
等等。
为什么我得到这个返回作为一个字符串?为了让 json 对象的字符串在 post 后返回,应该改变什么?
【问题讨论】:
标签: java android json apache post