У меня есть 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.И я написал 2 функции для вызова Async и вызова синхронизации для этого API.Но проблема в том, что мой метод 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) {
}
});
}