Java 改造 - android.os.NetworkOnMainThreadException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35481990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Retrofit - android.os.NetworkOnMainThreadException
提问by Joe Richard
I am using Retrofit 2 to get json and parse it to POJO. My purpose is getting one value of that object.
我正在使用 Retrofit 2 来获取 json 并将其解析为 POJO。我的目的是获得该对象的一个值。
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
My REST client:
我的 REST 客户端:
public interface MyClient {
@GET("/part1/part2")
Call<MyItem> getMyItem(@Query("param1") String param1,
@Query("param2") String param2,
@Query("param3") String param3);
}
HereI 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:
当我尝试运行此代码时,出现此错误:
android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147) at java.net.InetAddress.lookupHostByName(InetAddress.java:418) at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252) at java.net.InetAddress.getAllByName(InetAddress.java:215) at okhttp3.Dns$1.lookup(Dns.java:39) at okhttp3.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:173) at okhttp3.internal.http.RouteSelector.nextProxy(RouteSelector.java:139) at okhttp3.internal.http.RouteSelector.next(RouteSelector.java:81) at okhttp3.internal.http.StreamAllocation.findConnection(StreamAllocation.java:174) at okhttp3.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:127) at okhttp3.internal.http.StreamAllocation.newStream(StreamAllocation.java:97) at okhttp3.internal.http.HttpEngine.connect(HttpEngine.java:289) at okhttp3.internal.http.HttpEngine.sendRequest(HttpEngine.java:241) at okhttp3.RealCall.getResponse(RealCall.java:240) at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:198) at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:160) at okhttp3.RealCall.execute(RealCall.java:57) at retrofit2.OkHttpCall.execute(OkHttpCall.java:177) at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.execute(ExecutorCallAdapterFactory.java:87) at uz.cp.ox.data.MyRepository.getMyItem(MyRepository.java:31) at uz.cp.ox.presenters.MyPresenter.do(MyPresenter.java:30) at uz.cp.ox.activities.MyActivity.onClick(MyActivity.java:52) at android.view.View.performClick(View.java:4756) at android.view.View$PerformClick.run(View.java:19749) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5221) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147) at java.net.InetAddress.lookupHostByName(InetAddress.java:418) at java.net.InetAddress.getAllByNameImpl(InetAddress.java: 252) 在 java.net.InetAddress.getAllByName(InetAddress.java:215) 在 okhttp3.Dns$1.lookup(Dns.java:39) 在 okhttp3.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:173) 在 okhttp3.internal.http.RouteSelector.nextProxy(RouteSelector.java:139) 在 okhttp3.internal.http.RouteSelector.next(RouteSelector.java:81) 在 okhttp3.internal.http.StreamAllocation.findConnection(StreamAllocation.java) :174) 在 okhttp3.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:127) 在 okhttp3.internal.http.StreamAllocation.newStream(StreamAllocation.java:97) 在 okhttp3.internal.http.HttpEngine.connect(HttpEngine.爪哇:289) 在 okhttp3.internal.http.HttpEngine.sendRequest(HttpEngine.java:241) 在 okhttp3.RealCall.getResponse(RealCall.java:240) 在 okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:198) 在 okhttp3。 RealCall.getResponseWithInterceptorChain(RealCall.java:160) at okhttp3.RealCall.execute(RealCall.java:57) at retrofit2.OkHttpCall.execute(OkHttpCall.java:177) atretrofit2。ExecutorCallAdapterFactory$ExecutorCallbackCall.execute(ExecutorCallAdapterFactory.java:87) at uz.cp.ox.data.MyRepository.getMyItem(MyRepository.java:31) at uz.cp.ox.presenters.MyPresenter.do(MyPresenter.java:30)在 uz.cp.ox.activities.MyActivity.onClick(MyActivity.java:52) 在 android.view.View.performClick(View.java:4756) 在 android.view.View$PerformClick.run(View.java:19749) ) 在 android.os.Handler.handleCallback(Handler.java:739) 在 android.os.Handler.dispatchMessage(Handler.java:95) 在 android.os.Looper.loop(Looper.java:135) 在 android.app.ActivityThread.main(ActivityThread.java:5221) 在 java。 lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:第694章)
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?
我认为 Retrofit 会自动在后台线程中完成这项工作。或者我误会了什么。在这种情况下有什么问题以及如何解决?
采纳答案by NightSkyDev
I thought that Retrofit automatically does the job in the background thread.
我认为 Retrofit 会自动在后台线程中完成这项工作。
It does if you use the asynchronous version - enqueue
. You're using the synchronous version, which runs on the calling thread.
如果您使用异步版本 - enqueue
. 您使用的是同步版本,它在调用线程上运行。
Call it this way instead:
改为这样称呼它:
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
}
});
In onResponse(), use response.body()
to get your response, such as:MyItem myItem=response.body();
在 onResponse() 中,用于response.body()
获取您的响应,例如:MyItem myItem=response.body();
Edit: Fixed onResponse() & onFailure() signatures and added example to onRespnose().
编辑:修复了 onResponse() 和 onFailure() 签名并向 onRespnose() 添加了示例。
回答by Sai Soe Harn
You are calling webservice on main thread, that's why u got this error 'android.os.NetworkOnMainThreadException'.
您正在主线程上调用 webservice,这就是为什么您收到此错误“ android.os.NetworkOnMainThreadException”。
You can use the above coding answered by NightSkyDevto get the data what u want.
您可以使用NightSkyDev回答的上述编码来获取您想要的数据。
回答by Rahul Jain
In Retrofit Two Types of Method execution takes place- Enqueue- Works on background thread automatically handle by retrofit. Execute- Works on UI thread manually required to put in either background thread or take help of async task.
在方法执行的改造两种即告发生─ 排队在后台线程通过改装自动工作手柄- 。 执行- 在 UI 线程上手动工作,需要放入后台线程或获取异步任务的帮助。