【发布时间】:2014-08-24 17:23:15
【问题描述】:
我在让 HTTP GET 工作时遇到了一些麻烦。我尝试过使用 OKHttp 库和默认的 android HTTP 客户端。问题是当我使用默认的 http 客户端时,我在响应正文中得到了这个
org.apache.http.conn.BasicManagedEntity@424ab550
当我使用 okhttp 库时
com.squareup.okhttp.Call$RealResponseBody@424a6c58
假设响应正文包含一个 JSON 对象。如果我将 URL 粘贴到浏览器窗口中,则 JOSN 会正确返回。我还检查了服务器日志,并且响应从服务器正确发送。我正在从异步类调用 HTTP GET 方法。
使用默认 Android HTTP 客户端的 GET 方法:
public String getData(String url)
{
Log.w("Rakshak", "in the get Data data method");
Log.w("Rakshak", "URL: "+url);
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 20000000); //Timeout Limit
HttpResponse httpResponse;
try {
Log.w("Rakshak", "in the get data try");
HttpGet get = new HttpGet(url);
httpResponse = client.execute(get);
String response = httpResponse.getEntity().toString();
Log.w("Rakshak", "Get responce: "+response); // this posts "org.apache.http.conn.BasicManagedEntity@424ab550" insted of the JSON that am supposed to get
return response;
} catch(Exception e)
{
e.printStackTrace();
}
return "1";
}
使用 OkHTTP 库的 GET 方法:
public String getData(String url)
{
OkHttpClient client = new OkHttpClient();
//Log.w("Rakshak", "in the get Data data method ");
//Log.w("Rakshak", "URL: "+url);
Request request = new Request.Builder()
.url(url)
.build();
try {
Response response = client.newCall(request).execute();
response.toString();
Log.w("Rakshak", " in the service handeler"+response.body().toString()); // this posts "com.squareup.okhttp.Call$RealResponseBody@424a6c58" insted of the JSON that I supposed to get in the body.
return response.body().toString();
} catch (IOException e) {
e.printStackTrace();
return "failed";
}
}
我做错了什么,当我在浏览器窗口中通过相同的 url 时,为什么我无法从应用程序中获得正确的响应?
如果您需要查看更多代码,请告诉我。
干杯
【问题讨论】: