Sreedev
Sreedev

Reputation: 6653

401 unauthorized error for GET request with type Authorization = bearer token

I am making an HttpGet request with "Authorization" as header attaching bearer token. I am getting a 401 unauthorized error all the time.

I have tried retrofit, it didn't work so I reverted back to basic HTTP client. Then after a lot of research found that there is some error with DefaultHttp. So I changed to HTTPUrlConnection. Even after doing all these, I am still getting an unauthorized 401 error. What could I possibly do wrong here? Because this error still persists, I decided to stick to HTTPUrlConnection or DefaultHTTP and stay away from libraries.

Here is my code with HttpUrlConnection

        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection)
                            obj.openConnection();
        con.setRequestMethod("GET");

        String authString = "Bearer" + accessToken;
        con.setRequestProperty("Authorization", authString);

        int responseCode = con.getResponseCode();

        if (responseCode == HttpURLConnection.HTTP_OK) { // success
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    con.getInputStream()));
            String inputLine;
            response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

        } else {
            System.out.println("GET request not worked");
        }

Here is my DefaultHttp request

        StringBuilder builder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGetRequest = new HttpGet(url);
        httpGetRequest.addHeader("Authorization","Bearer"+accessToken);
        try {
            HttpResponse response = client.execute(httpGetRequest);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new 
                InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }
            }

Upvotes: 1

Views: 10351

Answers (3)

Sreedev
Sreedev

Reputation: 6653

The problem was resolved. I tried using retrofit and defaultHttpClient but both didn't worked for me because of some cookie issue. But using OKHttpClient it was straight forward and I was able to hit the server and get the response.

    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
            .url(mURL)
            .addHeader("Authorization", String.format("Bearer %s", bearerToken))
            .build();

        Response response = client.newCall(request).execute();
        return response.body().string();

Upvotes: 0

Muhammad Saad Rafique
Muhammad Saad Rafique

Reputation: 3189

Please use Fast Android Networking library its very easy to use and you can implement your logic in less than 5 mins. So please give it a try atleast. Below is the link to library:

https://github.com/amitshekhariitbhu/Fast-Android-Networking

Upvotes: 0

mad.meesh
mad.meesh

Reputation: 2776

add a whitespace after Bearer cus as it stands your concatenating Bearer with the token as one string

Upvotes: 2

Related Questions