简体   繁体   中英

401 Unauthorized Error using HttpURLConnection Android?

We have searched and searched and still cannot seem to get a resolution to this issue. We have a REST web service and are trying to access it from our Android app. The web service URL work when accessed from a web browser or from the Advanced Rest Client extension in Chrome. Our URL looks like:

http://10.52.1.1:8080/GPService/Tenants(Name=DefaultTenant)/Companies(Fabrikam,%20Inc.)/Items(128%20SDRAM).JSON

And once this is typed into the browser we are prompted for credentials. After credentials are entered, the JSON result is returned.

In our Android app we are trying the following:

    Authenticator.setDefault(new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("domain\\user", "password".toCharArray());
        }
    });

    URL url = new URL(urlstring);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(false);
    conn.setDoInput(true);
    conn.setRequestMethod("GET");
    conn.setConnectTimeout(60000);
    InputStream istream = conn.getInputStream();

Any ideas what we are doing wrong? We tried different methods, similar to this Connecting to remote URL which requires authentication using Java and http://www.muneebahmad.com/index.php/archives/127 but with no success at all, we are constantly getting the 401 Unauthorized error.

As per a comment received: our service is using NTLM authentication.

Thanks for any help!

conn.setRequestProperty("Authorization", "Basic " + Base64.encodeToString("usernameUsed:passwordUsed".getBytes(), Base64.NO_WRAP));

Above code worked for me.

I had the same issue. In my case, I was sending a timestamp (base encoded) as one of the headers. The device's (in which I was testing) time was set to a past time which made authorization failure.

(I know this post is old. Just added my experience, it might be of use to someone)

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