3

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");
}
Ravi
  • 30,829
  • 42
  • 119
  • 173
Kushal Bhalaik
  • 3,349
  • 5
  • 23
  • 46

1 Answers1

3

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
Community
  • 1
  • 1
Ravi
  • 30,829
  • 42
  • 119
  • 173