Search code examples
javabasic-authentication

IOException in Basic Authentication for HTTP url


I am hitting HTTP url with username:password using JAVA code. Below is my code

public static main (String args[]){
try{ 

                    String webPage = "http://00.00.000.000:8080/rsgateway/data/v3/user/start/";
        String name = "abc001";
        String password = "abc100";
        String authString = name + ":" + password;
        System.out.println("auth string: " + authString);
        byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
        String authStringEnc = new String(authEncBytes);
        URL url = new URL(webPage);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setUseCaches(true);
            connection.setRequestMethod("GET");
        connection.setRequestProperty("Authorization","Basic " +authStringEnc);
                    connection.setRequestProperty("Accept", "application/xml");
                    connection.setRequestProperty("Content-Type", "application/xml");
        InputStream is = connection.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);

        int numCharsRead;
        char[] charArray = new char[1024];
        StringBuffer sb = new StringBuffer();
        while ((numCharsRead = isr.read(charArray)) > 0) {
            sb.append(charArray, 0, numCharsRead);
        }
        String result = sb.toString();

        System.out.println("*** BEGIN ***");
        System.out.println(result);
        System.out.println("*** END ***");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

But I am getting 401 Error

java.io.IOException: Server returned HTTP response code: 401 for URL:

same url if i hit using curl then it is returning response. below is the curl command.

curl -u abc001:abc100 http://00.00.000.000:8080/rsgateway/data/v3/user/start/

Please help me resolve this.


Solution

  • The code you are getting is HTTP 401 Unauthorized, which means that the server isn't interpreting your basic authentication properly.

    Since you say that the curl command with the basic authentication you showed is working, I'll assume the problem is in your code.

    It looks like you tried to follow this code.

    The only error I can see (but I cannot test this to be sure) is that you just cast the byte[] to a String instead of encoding it with Base64.

    So you should change this:

    String authStringEnc = new String(authEncBytes);

    to this:

    String authStringEnc = Base64.getEncoder().encodeToString(authEncBytes);

    Also, you want to change this:

    byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());

    to this:

    byte[] authEncBytes = authString.getBytes();

    byte[] authEncBytes = authString.getBytes(StandardCharsets.UTF_8);