问题
I am learning how to use retrofit in android but whenever I try to retrieve data from the internet my app doesn't return anything My response doesn't come successful and I don't know how to fix the error currently I am trying to post and retrieve data from this URL using https://jsonplaceholder.typicode.com. I am unable to figure out what is causing this.
MainActivity
private void createpost() {
Post post2=new Post(1,"This is Title","10");
Call<Post> postCall= mWebService.createPost(post2);
postCall.enqueue(new Callback<Post>() {
@Override
public void onResponse(Call<Post> call, Response<Post> response) {
if (response.isSuccessful())
{
Log.d(TAG,"response.isSuccessful()");
mLog.setText(String.valueOf(response.code()));
showPost(response.body());
}
}
@Override
public void onFailure(Call<Post> call, Throwable t) {
}
});
}
Interface
public interface MyWebService {
String BASE_URL="https://jsonplaceholder.typicode.com/";
Retrofit retrofit=new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
@POST("posts")
Call<Post> createPost(@Body Post post);
}
回答1:
For unknown reason https://jsonplaceholder.typicode.com
is throwing socket timeout exception, in the mean time you can check another website with similar functionality https://reqres.in/
here is the sample code attached to post
final HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
final OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(httpLoggingInterceptor)
.build();
final String host = "https://reqres.in/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(HttpUrl.parse(host))
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
ReqResApi api = retrofit.create(ReqResApi.class);
api.createUser(new User("silentsudo", "dev"))
.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
System.out.println("Resp Success full: " + response.body().toString());
}
@Override
public void onFailure(Call<User> call, Throwable throwable) {
System.err.println("Error calling api");
throwable.printStackTrace();
}
});
Api
interface ReqResApi {
@POST("api/user")
Call<User> createUser(@Body User post);
}
POJO
class User {
private String name;
private String job;
public User(String name, String job) {
this.name = name;
this.job = job;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", job='" + job + '\'' +
'}';
}
}
来源:https://stackoverflow.com/questions/62074649/not-able-to-make-post-request-using-retrofit2-in-android