在改造2.0中的202状态中的响应

时间:2017-04-28 07:00:28

标签: android retrofit retrofit2 android-networking

我想将响应转换为JSON并将其显示给用户。我能够显示200响应,但在202中,我失败了。

{



            Log.d(TAG, "RESPONSE CODE" + response.code());
            if (response.code() == 200) {
                Gson gson = new Gson();
                SuccessResponse signupResponse = response.body();
                String sSignupResponse = gson.toJson(signUpResponse, SuccessResponse.class);
                try {

                } catch (JSONException e) {
                    e.printStackTrace();
                }


            } else if (response.code() == 202) {
                Log.d(TAG,"RESPONSE CODE IS "+"202 RIGHT");
                Gson gson = new Gson();
                SuccessResponse signupResponse = response.body();
                Log.d(TAG,"WHAT IS sSignupResponse"+signupResponse.toString());
                String sSignupResponse = gson.toJson(signUpResponse.toString());
                Log.d(TAG,"WHAT IS sSignupResponse"+sSignupResponse.toString());
                try {
                    JSONObject jsonObject=new JSONObject(sSignupResponse);
                    Log.d(TAG,"WHAT IS jsonObject"+jsonObject);
                } catch (JSONException e) {
                    e.printStackTrace();
                }


            } else {
                //request not successful (like 400,401,403 etc)
                //Handle errors
                Converter<ResponseBody, ErrorResponse> converter = ApiClient.getRetrofit().responseBodyConverter(ErrorResponse.class, new Annotation[0]);
                try {
                    ErrorResponse errors = converter.convert(response.errorBody());
                    dialogUtil.showOkDialog(errors.getMessage().toString());
                } catch (Exception e) {
                    dialogUtil.showOkDialog(e.getMessage().toString());
                }
            }

        }

我也应该为202做同样的事吗? 我用错误和代码创建了另一个像ErrorResponse的POJO,用ErrorResponse替换了SuccessRespone

4 个答案:

答案 0 :(得分:0)

试试这个:

String sSignupResponse = gson.toJson(signUpResponse);

而不是

String sSignupResponse = gson.toJson(signUpResponse, SuccessResponse.class);

答案 1 :(得分:0)

200(OK),201(创建 - 在服务器数据库中插入内容时)和204(无内容 - 服务器已处理您的请求而不返回任何内容)是corect。查看HTTP/1.1以查看Public Class ClassA(Of T) Private _someField As T Public Property SomeProperty As T Get Return Me._someField End Get Set(value As T) Me._someField = value End Set End Property Public Function DoSomeThing() As Type Return GetType(T) End Function End Class

中的所有回复代码

答案 2 :(得分:0)

您可以查看REST response代码HERE

如果response code与格式2xx匹配,则表示成功。 因此,在您的情况下,您应该检查response.isSuccessful()以检查response是否success,而不是手动检查response代码

答案 3 :(得分:0)

我得到了一个答案,就这样做。你知道202 Response.So做一个POJO类Response202.Now让SuccessResponse Class继承Response Class的属性。你现在完成了

SuccessResponse response202 = response.body();
                        Gson gson202 = new Gson();
                        String json202Str = gson202.toJson(response202, SuccessResponse.class);