我正在尝试使用 Retrofit2 发出 POST
请求。但我遇到的情况是 response.isSuccessful()
返回 false 并且我不知道如何调试它。我检查了后端日志,没有任何错误,什么也没有。
我确保请求的 URL 正确,所有参数也正确。我做错了什么?对我来说,似乎该请求甚至没有到达我的服务器。
这就是我所做的:
我有一个带有 getter 和 setter 的 User 类:
public class User {
@SerializedName("user_id")
@Expose
private int id;
@SerializedName("first_name")
@Expose
private String firstName;
@SerializedName("last_name")
@Expose
private String lastName;
public int getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
我有我的服务:
public interface APIService {
@POST("auth/register")
@FormUrlEncoded
Call<User> register(@Field("email") String email, @Field("password") String password);
}
现在我尝试执行它,它在响应 block 中返回 false:
private void registerUser(){
Call<User> registerCall = apiService.register(email, password);
registerCall.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
if(response.isSuccessful()){
int id = response.body().getId();
String firstName = response.body().getFirstName();
String lastName = response.body().getLastName();
}else{
System.out.println("ERROR "+response.raw().body());
}
}
@Override
public void onFailure(Call<User> call, Throwable t) {
}
});
}
编辑:这是 ApiUtils:
public class ApiUtils {
private ApiUtils() {}
public static final String BASE_URL = "https://api.mydomain.com/";
public static APIService getAPIService() {
return RetrofitClient.getClient(BASE_URL).create(APIService.class);
}
}
我做错了什么?我怎样才能进行更多调试?如有任何帮助,我们将不胜感激。
最佳答案
构建改造实例(您的 getApiService 方法)似乎存在问题,要查看 api 调用的日志和状态,您可以使用 http 日志拦截器:
private static Retrofit retrofit = null;
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new LogJsonInterceptor());
public static Retrofit getClient(String baseUrl) {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
}
return retrofit;
}
您可以使用拦截器查看 API 的原始 JSON 响应。希望这可以解决您的问题。
关于java - 改造 POST 请求 response.isSuccessful() 返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46012986/