Android 成功的 JSON 响应但 response.isSuccess() 不正确

标签 android json gson instagram

我终于从 Instagram 的 API 获得了访问 token 的响应。

final Call<TokenResponse> accessToken =  ServiceManager.createTokenService().getAccessToken(request);
accessToken.enqueue(new Callback<TokenResponse>() {
    @Override
    public void onResponse(Call<TokenResponse> call, Response<TokenResponse> response) {
        mtext.setText("hello");
      }

    @Override
    public void onFailure(Call<TokenResponse> call, Throwable t) {
        mtext.setText("failure");
    }
});

但是,当我检查 response.isSuccess() 是否失败时?我不明白这一点。

此外,我正在使用 Retrofit 2 并且我已经导入了 Gson,它应该自动正确映射数据吗?

最佳答案

在改造 2 中,onFailure 仅在 HTTP 请求期间发生网络或意外异常时调用。

response.isSuccess() 当http状态为2xx或3xx时返回true,否则返回false。

因此,当 isSuccess 为真时,您可以使用正确的数据模型来映射 json。当isSuccess为false时,你可以定义一个通用的错误模型来映射json。

[编辑]添加一些我在项目中使用 retrofit2 的简单代码 fragment ,希望这对您有所帮助。

@Override public void onResponse(Response<T> response, Retrofit retrofit) {
  onNetworkRequestFinished();
  if (response.isSuccess()) {
    onSuccess(response.body());
  } else {
    onFailed(response, retrofit);
  }
 }


@Override public void onSuccess(SignupResponse signupResponse) {
  ((JFragmentActivity) context).dialogHelper.dismissProgressDialog();
  sharedPreferenceHelper.saveLoginName(context, userName); 
  doAfterSignin(context, signupResponse);
}


public void onFailed(Response response, Retrofit retrofit) {
  Converter<ResponseBody, JErrorReponse> errorConverter =
    retrofit.responseConverter(JErrorReponse.class, new Annotation[0]);

    try {
      JErrorReponse error = errorConverter.convert(response.errorBody());
      if (error != null) {
        JToast.toastLong(error.msg);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

JErrorResponse.java

public class JErrorReponse implements Serializable {
  public int status;
  public String msg;
  public Object err;
}

注册响应.java

public class SignupResponse extends BaseResponse {

  public UserLoginData data;
}

用户登录数据.java

public class UserLoginData implements Serializable {
  @SerializedName("u_id") public int uId;

  @SerializedName("username") public String userName;

  public String icon;
}

关于Android 成功的 JSON 响应但 response.isSuccess() 不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35544765/

相关文章:

java - proguard 和 jdom 错误编译 android APK

java - Android 调试 InetAddress.isReachable

Android Kotlin 向数据类添加具有值的附加字段

android - 从 API 8 开始获取用户/所有者个人资料联系 URI 和用户图像

javascript - 将 JSON 文件的内容嵌入到页面中

json - Powershell & Curl - 在单引号 JSON 正文中使用变量

android - 如何在 Retrofit 中解析没有任何对象的 JSON 数组?

javascript - 在nodejs中解析具有格式键值的数组

java - 使用 gson 从 json 中删除 null 属性

java - 如何将这个 JSON 响应转换为 POJO?