Click here to Skip to main content
15,892,161 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
I have a webapi project where my android client retreives data. The webapi is secured by BearerToken authentication. The client is aware of that and successfully gets a bearer token.

Now my problem is, that on every second request to the same url with the same parameters I get a 401 Unauthorized response from the webapi. What drives me crazy is that the Bearer token does not change between the two requests and the header is correctly set on both requests.

How is that possible?

Here is my android code:

Java
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(args[0]);
httpget.addHeader("Authorization", "Bearer " + BearerToken);

// Execute the request
HttpResponse response;

JSONArray arr = new JSONArray();
try {
   response = httpclient.execute(httpget);

   HttpEntity entity = response.getEntity();

   if (entity != null && response.getStatusLine().getStatusCode() == 200) {
            // A Simple JSON Response Read
            InputStream instream = entity.getContent();
            String result = convertStreamToString(instream);
            arr=new JSONArray(result);
            instream.close();

        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        Log.e("EXCEPTION",e.toString());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        Log.e("EXCEPTION",e.toString());
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        Log.e("EXCEPTION",e.toString());
    }
Posted
Comments
pasztorpisti 8-Apr-14 18:53pm    
To me this seems to be an impossible-to-answer question. Only you have the environment to debug this issue out.

1 solution

I found out that DefaultHttpClient not always works as expected. It seems that this one will get deprecated sooner or later.

I now use HttpURLConnection for accessing data over HTTP. This works better and also has more options to configure.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900