Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting "401" response code when trying to connect local server?

I've a local server which runs on http://192.168.0.101:8080/. Whenver I try to ping the server using following code I get response code as "401". My server requires password as "12345"

try {
    URL url = new URL("http://192.168.0.101:8080/");  
    HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
    urlc.setRequestMethod("GET");
    urlc.setConnectTimeout(10 * 1000);          // 10 s.
    urlc.connect();

    System.out.println("code" + urlc.getResponseCode());
    if (urlc.getResponseCode() == 200) {        // 200 = "OK" code (http connection is fine).
         System.out.println("Connection success");

    } else {
        System.out.println("Connection nada");
    }
} catch (MalformedURLException e1) {
    System.out.println("MalformedURLException");
} catch (IOException e) {
    System.out.println("IOException nada");
}
like image 423
Kushal Bhalaik Avatar asked May 29 '26 02:05

Kushal Bhalaik


1 Answers

Http Status Code 401, indicates unauthorized access and you are required to send WWW-Authenticate header along with your request.

The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource. The server generating a 401 response MUST send a WWW-Authenticate header field (Section 4.1) containing at least one challenge applicable to the target resource.

There are different authentication scheme available (i.e. Basic, Digest or OAuth) one of them is Basic authentication, as shown follow.

//you code
//
String userCredentials = "username:password";
String basicAuth = "Basic " + new String(new Base64().encode(userCredentials.getBytes()));
urlc.setRequestProperty ("Authorization", basicAuth);
urlc.setRequestMethod("GET");
// your code
like image 94
Ravi Avatar answered May 31 '26 10:05

Ravi