[英]How to make an asynchronous response a synchronous response (Java: Android Studio)
[英]Synchronous connect to API in android studio not work but Asynchronous worked
我有一個API,它可以在異步模式下工作,但不能在同步模式下工作。 我有一個ApiUtils課:
public class ApiUtils {
private ApiUtils() {}
public static final String BASE_URL = "http://jsonplaceholder.typicode.com/";
public static APIServices getAPIService() {
return RetrofitClient.getClient(BASE_URL).create(APIServices.class);
}
}
並具有RetrofitClient類:
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl) {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
我的ViewModel類是:
public class Post {
@SerializedName("title")
@Expose
private String title;
@SerializedName("body")
@Expose
private String body;
@SerializedName("userId")
@Expose
private Integer userId;
@SerializedName("id")
@Expose
private Integer id;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Override
public String toString() {
return "Post{" +
"title='" + title + '\'' +
", body='" + body + '\'' +
", userId=" + userId +
", id=" + id +
'}';
}
}
我的gradle依賴項是:
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.google.code.gson:gson:2.8.4'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
而且我在android manifest中授予了互聯網許可。 我為該api編寫了2個用於Async調用和Sync調用的函數。 但是問題是我的Async方法有效,但Sync方法卻無效:
//Not work
private void SyncCall() {
Call<Post> ins= mAPIServices.savePost("test title", "test body", 12);
try {
String s =ins.execute().body().toString();
} catch (IOException e) {
e.printStackTrace();
}
}
//Worked
private void AsyncCall() {
mAPIServices.savePost("test title", "test body", 12)
.enqueue(new Callback<Post>() {
@Override
public void onResponse(Call<Post> call, Response<Post> response) {
String s = response.body().toString();
}
@Override
public void onFailure(Call<Post> call, Throwable t) {
}
});
}
我可以找到解決方案。 我們必須創建一個像這樣的新類:
public class InnerClass extends AsyncTask {
@Override
protected Post doInBackground(Object[] objects) {
APIServices mAPIServices = ApiUtils.getAPIService();
Call<Post> ins= mAPIServices.savePost("test title", "test body", 12);
Post ret=new Post();
try {
ret =ins.execute().body();
} catch (IOException e) {
e.printStackTrace();
}
return ret;
}
}
然后我們可以使用以下代碼同步調用api:
AsyncTask s=new InnerClass().execute();
try {
Post a=(Post)s.get();
}
catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.