如何解决 401 错误

how to solve 401 error

我正在尝试从两个 EditText 视图发送 JSON 格式数据(使用 Volley)和一种方法 return 唯一设备 ID 到 URL 从我的 Android 申请,我收到 “[8970] BasicNetwork.performRequest:https://gorountsiallyetlasornall:5wxGq5UNlY6wdWmNAyYPVVrN@bulberadev.cloudant.com/notebook 的意外响应代码 401”

这是我的方法:

private void doPost() {
    final String url = "https://gorountsiallyetlasornall:5wxGq5UNlY6wdWmNAyYPVVrN@bulberadev.cloudant.com/notebook";
    final String deviceId = getDeviceId(getApplicationContext());


    try {
        try {
            JSONObject jsonObject = new JSONObject();
            String title = editTitle.getText().toString();
            String content = editContent.getText().toString();
            jsonObject.put("title", title);
            jsonObject.put("content", content);
            jsonObject.put("deviceId", "<" + deviceId + ">");

        } catch (JSONException e) {
            e.printStackTrace();
        }
        requestQueue = Volley.newRequestQueue(this);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
                url, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    VolleyLog.v("Response:%n %s", response.toString(4));
                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // Log.e("VOLLEY", "ERROR");
                    }
                });
        requestQueue.add(jsonObjectRequest);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

格式应为:

   {
"title":"Birth day",
"content":"Buy a gift for my mom!",
"deviceId":"<Device ID>"
}

401 是未经授权的错误。

https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_Error

这意味着用户和密码未被识别。您通过 URL 提供它,但这仅适用于浏览器。如果您使用的服务接受基本 HTTP 授权 headers,此代码将为您提供所需的 headers:

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    HashMap<String, String> params = new HashMap<String, String>();
    String creds = String.format("%s:%s","USERNAME","PASSWORD");
    String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.DEFAULT);
    params.put("Authorization", auth);
    return params;
}

原始代码来自 https://whosebug.com/a/18980454/3286819

当然,用户名和密码需要是您自己的。在这种情况下:

更多信息:https://yakivmospan.wordpress.com/2014/04/04/volley-authorization/

错误 401 是未经授权的 HTTP 错误。这不是 Volley 或 android 相关的故障。在这种情况下,您提供的 URL https://gorountsiallyetlasornall:5wxGq5UNlY6wdWmNAyYPVVrN@bulberadev.cloudant.com/notebook

也不能被 Volley 解释为登录。这个 url 有时被 cURL 和其他工具用来将密码中的用户名硬编码到基本身份验证 HTTP 的 URI 中。

为此,您的用户名是 gorountsiallyetlasornall,密码是 5wxGq5UNlY6wdWmNAyYPVVrN。

根据 Basic Autentication,解释 https://luckymarmot.com/paw/doc/HTTP_Basic_Auth 它需要转换为 Base 64,然后添加到请求的 header。

我已将您的用户名和密码转换为 Basic Auth base 64 编码字符串,供您参考。

Z29yb3VudHNpYWxseWV0bGFzb3JuYWxsOjV3eEdxNVVObFk2d2RXbU5BeVlQVlZyTg==

通过扩展 Volley 请求并将函数 getHeaders 覆盖到 return 具有以下键值对的 HashMap,将其添加到您的 Volley header。

"Authorization" , "Basic Z29yb3VudHNpYWxseWV0bGFzb3JuYWxsOjV3eEdxNVVObFk2d2RXbU5BeVlQVlZyTg"

您的请求现在可以工作了。

如果您需要更详细的解释,请告诉我。

PS。希望您在问题中发布的值不是您的真实用户名和密码。如果是这样,那以后就不要这样做了。