我想使用改造从服务器上获取数据。我的服务器将数据作为字符串json发送。 我创建这样的服务器:
public class ServiceGenerator {
public static final String BASE_URL = "http://192.168.100.73/ChartReport/Service1.svc/";
static OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(1, TimeUnit.MINUTES)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.build();
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create());
private static Retrofit retrofit = builder.build();
public static <S> S createService(Class<S> serviceClass) {
return retrofit.create(serviceClass);
}
}
然后我创建了一个客户端,如blow:
public interface IReportCLient {
@POST("json/GetDataReport")
Call<ResponseBody> getReporst();
}
我已经习惯了自己的活动:
IReportCLient service = ServiceGenerator.createService(IReportCLient.class);
Call<ResponseBody> reporst = service.getReporst();
reporst.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
JsonObject post = new JsonObject().get(response.body().string()).getAsJsonObject();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
当我第一次在调试模式下运行应用程序时,我通过以下命令获取数据:
response.body().string()
但是当我再次运行response.body().string()
时,我的结果立即为空?
会发生什么?
答案 0 :(得分:0)
string()
方法只能在RequestBody
上调用一次。因此,如果您尝试再次调用它,它将返回空字符串。调试也是如此。如果您在调试时尝试对表达式response.body().string()
求值,则您的实际方法将获得空字符串。
HTTP响应。此类的实例不是不可变的: 响应主体是一次性值,只能使用一次,并且 然后关闭。所有其他属性都是不可变的。 https://square.github.io/okhttp/3.x/okhttp/okhttp3/Response.html
也请阅读https://stackoverflow.com/a/32307866/6168272
这就是我从响应对象获得JsonObject
的方式。您可以尝试一下。
private JSONObject parseJsonFromResponse(Response response) {
ResponseBody responseBody = response.body();
if (responseBody != null) {
try {
return new JSONObject(responseBody.string());
} catch (JSONException | IOException e) {
e.printStackTrace();
return new JSONObject();
}
} else return new JSONObject();
}