android Retrofit 注意事项

来源:互联网 发布:java相关文献 编辑:程序博客网 时间:2024/05/18 16:17

 1、在Retrofit使用中,获取服务器数据可能会出现以下错误:org.json.JSONException: End of input at character 0 of

原代码如下:

@Override            public void onResponse(Call call, Response response) throws IOException {                if (response.isSuccessful()) {                    Log.d(TAG, response.body().string());                    String a=response.body().string();                    try {                        JSONObject forecast = new JSONObject(a);                    } catch (JSONException e) {                        e.printStackTrace();                    }                } else {                    alertUserAboutError();                }            }
此原因是因为a为“”,但我看了打印日志,response.body().string()是有值的,百思不得解,所以debug了以下,a还真是“”,为什么打印出来是有值,到a就没值了呢?Google了以下,解释如下:



down voteaccepted

Answer : Response object should of Generic type - ResponseBody
See below Correct code for reference. 
Now response.body() method will return object ResponseBody i.e.

ResponseBody rb = response.body(); rb.string();

Here ResponseBody have method string() which returns String object but internally string() method calls Util.closeQuietly(source); which makes response empty once method string() gets called.

Just remove Log.d(TAG, response.body().string()); and follow below code.


Reference - okhttp3.ResponseBody.java

error : org.json.JSONException: End of input at character 0

Correct code :

@Overridepublic void onResponse(Call call, Response<ResponseBody> response) throws IOException {   if (response.isSuccessful()) {      String remoteResponse=response.body().string();      Log.d(TAG, remoteResponse);      try {          JSONObject forecast = new JSONObject(remoteResponse);      } catch (JSONException e) {           e.printStackTrace();      }   }}

其实就是说,在response.body()的string()方法里,string()就执行了Util.closeQuietly(source)方法,将string设置为“”了,解决方法就是用1个string把它保留下来。

原创粉丝点击