简体   繁体   English

如何解决401错误

[英]how to solve 401 error

I am trying to sent JSON format data (using Volley) from two EditText-views and a method that return unique Device ID to a URL from my Android application and I receive "[8970] BasicNetwork.performRequest: Unexpected response code 401 for https://gorountsiallyetlasornall:5wxGq5UNlY6wdWmNAyYPVVrN@bulberadev.cloudant.com/notebook " 我试图从两个EditText视图发送JSON格式的数据(使用Volley),并且从我的Android应用程序向URL返回唯一的设备ID的方法,但我收到“ [8970] BasicNetwork.performRequest:HTTP的意外响应代码401 : //gorountsiallyetlasornall:5wxGq5UNlY6wdWmNAyYPVVrN@bulberadev.cloudant.com/notebook

Here is My method: 这是我的方法:

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();
    }

}

it should be in a format : 它应采用以下格式:

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

A 401 is an Unauthorized error. 401是未经授权的错误。

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

This means that the user and password is not getting recognized. 这意味着无法识别用户和密码。 You're providing it by means of the URL, but this only works for the browser. 您是通过URL提供的,但这仅适用于浏览器。 If the service you're using accepts Basic HTTP authorization headers, this code will provide you the needed headers: 如果您使用的服务接受基本HTTP授权标头,则此代码将为您提供所需的标头:

@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;
}

Original code from https://stackoverflow.com/a/18980454/3286819 来自https://stackoverflow.com/a/18980454/3286819的原始代码

Of course, username and password needs to be your own. 当然,用户名和密码必须是您自己的。 In this case: 在这种情况下:

Some more info: https://yakivmospan.wordpress.com/2014/04/04/volley-authorization/ 一些更多信息: https : //yakivmospan.wordpress.com/2014/04/04/volley-authorization/

Error 401 is an HTTP error for unauthorised. 错误401是未经授权的HTTP错误。 This is not a Volley or android related fault. 这不是Volley或android相关的错误。 In this case the URL you have provided https://gorountsiallyetlasornall:5wxGq5UNlY6wdWmNAyYPVVrN@bulberadev.cloudant.com/notebook 在这种情况下,您提供的URL https:// gorountsiallyetlasornall:5wxGq5UNlY6wdWmNAyYPVVrN@bulberadev.cloudant.com/notebook

Cannot be interpreted by Volley as a login either. Volley也不能将其解释为登录名。 This url is sometimes used by cURL and other tools to hardcode the username in password into the URI for Basic Authentication HTTP. cURL和其他工具有时会使用此url将密码中的用户名硬编码到基本身份验证HTTP的URI中。

For this your username is gorountsiallyetlasornall and your password is 5wxGq5UNlY6wdWmNAyYPVVrN. 为此,您的用户名是gorountsiallyetlasornall,密码是5wxGq5UNlY6wdWmNAyYPVVrN。

According to Basic Autentication, explained https://luckymarmot.com/paw/doc/HTTP_Basic_Auth It needs to be converted to Base 64 then added to the header of the request. 根据基本认证,解释如下:https: //luckymarmot.com/paw/doc/HTTP_Basic_Auth需要将其转换为Base 64,然后添加到请求的标头中。

I have converted your username and password into a Basic Auth base 64 encoded String for you bellow. 我已将您的用户名和密码转换为Basic Auth base 64编码的字符串,以供您使用。

Z29yb3VudHNpYWxseWV0bGFzb3JuYWxsOjV3eEdxNVVObFk2d2RXbU5BeVlQVlZyTg==

Add this into your Volley header by extending a Volley request and overriding the function getHeaders to return a HashMap with the following key value pair. 通过扩展Volley请求并覆盖函数getHeaders以返回具有以下键值对的HashMap,将其添加到Volley标头中。

"Authorization" , "Basic Z29yb3VudHNpYWxseWV0bGFzb3JuYWxsOjV3eEdxNVVObFk2d2RXbU5BeVlQVlZyTg"

Your request will now work. 您的请求现在可以使用。

Please let me know if you want a more detailed explanation. 如果您需要更详细的说明,请告诉我。

PS. PS。 Hopefully the values you posted in your question is not your real username and password. 希望您在问题中发布的值不是您的真实用户名和密码。 If so, then don't do that in the future. 如果是这样,那么将来就不要这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM