【问题标题】:how to get response body in okhttp when code is 401当代码为 401 时如何在 okhttp 中获取响应正文
【发布时间】:2017-07-15 04:31:06
【问题描述】:

我正在使用 okHttp 3.2.0,这里是构建请求对象的代码

MediaType JSON = MediaType.parse(AppConstants.CONTENT_TYPE_VALUE_JSON);
RequestBody body = RequestBody.create(JSON, requestBody);


    HttpUrl url = new HttpUrl.Builder()
                                    .scheme("http")
                                    .host("192.168.0.104")
                                    .port(8080)
                                    .addPathSegment("mutterfly-server")
                                    .addPathSegment("j_spring_security_check")
                                    .addQueryParameter("j_username", jsonObject.getString("emailId"))
                                    .addQueryParameter("j_password", jsonObject.getString("password"))
                                    .build();

     request = new Request.Builder()
                                    .addHeader(AppConstants.CONTENT_TYPE_LABEL, AppConstants.CONTENT_TYPE_VALUE_JSON)
                                    .addHeader(AppConstants.ACCEPT_LABEL, AppConstants.CONTENT_TYPE_VALUE_JSON)
                                    .url(url)
                                    .post(body)
                                    .build();

这是我解析响应的方式

client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, final Response response) throws IOException {

                    String respBody;
                    if (response.isSuccessful()) {
                        if (response.body() != null) {
                            respBody = response.body().string();
                            Log.i(TAG, respBody);
                            response.body().close();
                            if (AppMethods.checkIfNull(loginParserListener)) {
                                try {
                                    final VUser user = AppMethods.getGsonInstance().fromJson(respBody, VUser.class);
                                } catch (Exception e) {

                                }
                            }
                        }
                    } else {

                        switch (response.code()){
                            case 401:
                                String body="HTTP_UNAUTHORIZED";
                                break;
                        }
                    }
                }
            });

这是身份验证失败时的理想响应(来自 web rest 客户端)。

{"msgDesc":"The username or password you entered is incorrect..","statusCode":401}

编辑:

response.toString() 返回

Response{protocol=http/1.1, code=401, message=Unauthorized, url=http://192.168.0.104:8080/mutterfly-server/j_spring_security_check?j_username=s@s.s&j_password=1}

response.body().toString() 返回

okhttp3.internal.http.RealResponseBody@528ae030

我想获取响应正文中的“msgDesc”。有什么方法可以返回这个字符串吗?

【问题讨论】:

    标签: android okhttp okhttp3


    【解决方案1】:

    试试这个:

    switch (response.code()){
            case 401:
               JsonObject object=new JsonObject(response.body().string());
               String body=object.getString("msgDesc");
               break;
    }
    

    【讨论】:

    • response.toString() 返回 Response{protocol=http/1.1, code=401, message=Unauthorized, url=192.168.0.104:8080/mutterfly-server/…}
    • 感谢您的回复,但我已经编辑了帖子并检查了回复
    • 只要把toString()改成string()
    【解决方案2】:

    这很奇怪,但是 OkHttp 背后的公司 Square 选择不使用 'toString()' 而是使用 'string()' 作为将正文作为字符串获取的方法。

    所以这行得通;

    String string = response.body().string();
    //convert to JSON and get your value
    

    但这不是:

    String string = response.body().toString();
    

    【讨论】:

    • 是的,这很奇怪。
    • getString() 也不太可能导致小错误。我盯着我的代码,与我正在使用的示例相比,只是看不到这一点。 (给自己的一课 - 避免“getters”使用一个单词的函数名称)
    【解决方案3】:

    401 表示permission denied

    检查您的token 是否有效或user/password 是否正确。

    【讨论】:

    • 我尝试登录用户时没有生成令牌。而且我想测试用户输入错误凭据时的情况,这样我就可以用从服务器收到的“msgDesc”通知用户..
    猜你喜欢
    • 2014-11-27
    • 2015-09-11
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    • 2016-06-16
    • 2014-09-20
    • 1970-01-01
    • 2018-12-27
    相关资源
    最近更新 更多