问题描述
我正在使用Retrofit 2来获取json并将其解析为POJO。我的目的是获得该对象的一个值。
I am using Retrofit 2 to get json and parse it to POJO. My purpose is getting one value of that object.
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
我的REST客户端:
public interface MyClient {
@GET("/part1/part2")
Call<MyItem> getMyItem(@Query("param1") String param1,
@Query("param2") String param2,
@Query("param3") String param3);
}
我找到了创建服务的绝佳工具:
Here I found great great tool to create service:
public class ServiceGenerator {
public static final String API_BASE_URL = "http://my.api.com";
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create());
public static <S> S createService(Class<S> serviceClass) {
Retrofit retrofit = builder.client(httpClient.build()).build();
return retrofit.create(serviceClass);
}
}
然后我使用服务生成器类创建新服务:
Then I am creating new service using Service generator class:
MyClient api = ServiceGenerator.createService(MyClient.class);
Call<MyItem> call = api.getMyItem(param1, param2, param3);
MyItem myItem= null;
try {
myItem= call.execute().body();
Log.d("MyTag", myItem.getValue());
} catch (IOException e) {
e.printStackTrace();
}
当我尝试运行此代码时,我收到此错误:
When I am trying to run this code I am getting this error:
我认为Retrofit会自动在后台线程中完成工作。或者我误解了一些事情。这种情况有什么问题以及如何解决?
I thought that Retrofit automatically does the job in the background thread. Or I misunderstood something. What is wrong in this situation and how to solve it?
推荐答案
如果你使用异步版本 - enqueue会这样做
。您正在使用在调用线程上运行的同步版本。
It does if you use the asynchronous version - enqueue
. You're using the synchronous version, which runs on the calling thread.
这样称呼:
MyClient api = ServiceGenerator.createService(MyClient.class);
Call<MyItem> call = api.getMyItem(param1, param2, param3);
call.enqueue(new Callback<MyItem>() {
@Override
public void onResponse(Call<MyItem> call, Response<MyItem> response) {
MyItem myItem=response.body();
}
@Override
public void onFailure(Call<MyItem> call, Throwable t) {
//Handle failure
}
});
在onResponse()中,使用 response.body()
获取您的回复,例如:
MyItem myItem = response.body();
In onResponse(), use response.body()
to get your response, such as:
MyItem myItem=response.body();
编辑:修正onResponse()& onFailure()签名并在onRespnose()中添加了示例。
Fixed onResponse() & onFailure() signatures and added example to onRespnose().
这篇关于改造 - android.os.NetworkOnMainThreadException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!