Android 上的摘要获得 401

Digest on Android get 401

我正在尝试对此服务器进行摘要式身份验证 http://52.16.207.138/api/v0.1/device/999 用户 = 5588031263bf4457a7641c07 并通过网络浏览器传递 = 5588031263bf4457a7641c08,我得到一个 200 http 代码和一个 json 一些状态。

我的android代码:

private JSONObject POST() throws JSONException {
    JSONObject response = null;

    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("5588031263bf4457a7641c07", "5588031263bf4457a7641c08".toCharArray());
        }
    });

    try {

        URL url1 = new URL("http://52.16.207.138/api/v0.1/device/999");
        HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
        conn.setRequestMethod(GET);
        conn.connect();

        int status = conn.getResponseCode();
        InputStream is;

        if(status >= HttpURLConnection.HTTP_BAD_REQUEST)
            is = conn.getErrorStream();
        else
            is = conn.getInputStream();

        Log.d("RespuestaHTTP",String.valueOf(status));

        byte[] buffer = new byte[8196];
        int readCount;
        StringBuilder builder = new StringBuilder();
        while ((readCount = is.read(buffer)) > -1) {
            builder.append(new String(buffer, 0, readCount));
        }
        response = new JSONObject(builder.toString());
        Log.d("Respuesta",response.toString());

        conn.disconnect();

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return response;
}

但我总是收到 401 响应,我不知道自己做错了什么。

有人可以帮助我吗???

06-22 18:57:17.797 1708-1750/com.example.urbanclouds.pruebasdigest D/RespuestaHTTP﹕ 401

已将我的回答复制到

HttpUrlConnection 不支持摘要认证。如果您的客户端必须使用 Digest 进行身份验证,您有以下几种选择:

  • 编写您自己的 HTTP 摘要实现。如果您知道需要向哪些服务器进行身份验证并且可以忽略不需要的摘要规范部分,那么这可能是一个不错的选择。这是一个实现摘要子集的示例:https://gist.github.com/slightfoot/5624590.
  • 使用外部库 bare-bones-digest,它是 Android 的摘要库。您可以使用它来解析 Digest 质询并生成对它们的响应。它支持常见的摘要用例和一些很少使用的用例,可以在 HttpURLConnection.
  • 之上使用
  • 使用OkHttp together with okhttp-digest,这是一个为O​​kHttp添加Http Digest支持的插件。使用 OkHttp 支持 Digest 很容易,只需添加 okhttp-digest 作为身份验证器,您将获得透明的 Http 摘要支持。如果您已经在使用 OkHttp 或者可以切换到它,这可能是一个有吸引力的选择。
  • 使用支持 Digest 的 Apache HttpClient。包含此选项主要是为了完成,因为 Google 不建议使用 HttpClient 并且已弃用它。