首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >改装2-零响应体

改装2-零响应体
EN

Stack Overflow用户
提问于 2015-11-17 13:00:40
回答 1查看 33K关注 0票数 17

我正在尝试用Retrofit 2转换以下响应

代码语言:javascript
复制
{
    "errorNumber":4,
    "status":0,
    "message":"G\u00f6nderilen de\u011ferler kontrol edilmeli",
    "validate":[
        "Daha \u00f6nceden bu email ile kay\u0131t olunmu\u015f. L\u00fctfen giri\u015f yapmay\u0131 deneyiniz."
    ]
}

但我总是在onResponse方法中得到onResponse响应。因此,我尝试使用response.errorBody.string()查看响应的错误体。错误正文包含与原始响应完全相同的内容。

以下是我的服务方法、Retrofit对象和响应数据解密:

代码语言:javascript
复制
@FormUrlEncoded
@POST("/Register")
@Headers("Content-Type: application/x-www-form-urlencoded")
Call<RegisterResponse> register(
        @Field("fullName")  String fullName,
        @Field("email")     String email,
        @Field("password")  String password);

public class RegisterResponse {
    public int status;
    public String message;
    public int errorNumber;
    public List<String> validate;
}

OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Response response = chain.proceed(chain.request());
        final String content = UtilityMethods.convertResponseToString(response);
        Log.d(TAG, lastCalledMethodName + " - " + content);
        return response.newBuilder().body(ResponseBody.create(response.body().contentType(), content)).build();
    }
});
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .client(client)
        .build();
domainSearchWebServices = retrofit.create(DomainSearchWebServices.class);

我已经用jsonschema2pojo控制了response JSON,看看我是否修改了响应类wright,这似乎还可以。

为什么重装不能改变我的反应?

更新

现在,作为一项工作,我正在建立我的反应从错误的主体。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-17 13:35:54

我已经解决了这个问题。当我提出一个错误的请求(HTTP 400)时,Retrofit不会转换响应。在这种情况下,您可以使用response.errorBody.string()访问原始响应。之后,您可以创建一个新的Gson并手动转换它:

代码语言:javascript
复制
if (response.code() == 400 ) {
    Log.d(TAG, "onResponse - Status : " + response.code());
    Gson gson = new Gson();
    TypeAdapter<RegisterResponse> adapter = gson.getAdapter(RegisterResponse.class);
    try {
        if (response.errorBody() != null)
            registerResponse = 
                adapter.fromJson(
                    response.errorBody().string());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
票数 48
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33757619

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档