我正在为调用改造同步请求编写此代码:
public String LOGININTO() throws IOException {
final String[] message = {""};
LOGININTERFACE taskService = ServiceGenerator.createService(LOGININTERFACE.class);
Call<LGOINMODEL> tasks = taskService.savePost("0016642902","0016642902","password");
LGOINMODEL model=null;
model=tasks.execute().body();
return "OK";
}
但是在运行时我的代码会出现此错误:
在
Caused by: android.os.NetworkOnMainThreadException retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.execute(ExecutorCallAdapterFactory.java:91)
我该如何解决这个问题?
感谢。
答案 0 :(得分:1)
将您的执行包裹在new Thread()
:
public String LOGININTO() throws IOException {
final String[] message = {""};
LOGININTERFACE taskService = ServiceGenerator.createService(LOGININTERFACE.class);
Call<LGOINMODEL> tasks = taskService.savePost("0016642902","0016642902","password");
LGOINMODEL model=null;
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
model=tasks.execute().body();
}
});
thread.start();
return "OK";
}
答案 1 :(得分:-2)
请使用以下方法:
task.enqueue(new Callback<LGOINMODEL>() {
@Override
public void onResponse(Call<LGOINMODEL> call, Response<LGOINMODEL> response) {
}
@Override
public void onFailure(Call<LGOINMODEL> call, Throwable t) {
}
});
这可以解决您的问题:)