简体   繁体   中英

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 "

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.

https://en.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. If the service you're using accepts Basic HTTP authorization headers, this code will provide you the needed 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;
}

Original code from 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/

Error 401 is an HTTP error for unauthorised. This is not a Volley or android related fault. In this case the URL you have provided https://gorountsiallyetlasornall:5wxGq5UNlY6wdWmNAyYPVVrN@bulberadev.cloudant.com/notebook

Cannot be interpreted by Volley as a login either. This url is sometimes used by cURL and other tools to hardcode the username in password into the URI for Basic Authentication HTTP.

For this your username is gorountsiallyetlasornall and your password is 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.

I have converted your username and password into a Basic Auth base 64 encoded String for you bellow.

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.

"Authorization" , "Basic Z29yb3VudHNpYWxseWV0bGFzb3JuYWxsOjV3eEdxNVVObFk2d2RXbU5BeVlQVlZyTg"

Your request will now work.

Please let me know if you want a more detailed explanation.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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