0

I am sending Https request with username and password through 2 ways but in both the cases I am getting Error 401- Unauthorized error

  1. direct connection through URLConnection

    try {
        URL url = new URL("https://xxx.xxxxx.com/v1/limit/5");
        URLConnection urlConnection = url.openConnection();
        HttpsURLConnection connection = null;
        if(urlConnection instanceof HttpsURLConnection) {
            String authStr = "username"+":"+"password";
            byte[] bytesEncoded = Base64.encodeBase64(authStr.getBytes());
            String authEncoded = new String(bytesEncoded);
            connection = (HttpsURLConnection) url.openConnection();
            connection.setRequestProperty("Authorization", "Basic "+authEncoded);
         } else {
             System.out.println("Please enter an HTTPs URL.");
             return;
         }
    
         BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
         String urlString = "";
         String current;
         while((current = in.readLine()) != null) {
             urlString += current;
         }
         System.out.println(urlString);
    } catch(IOException e) {
        e.printStackTrace();
    }
    
  2. Connection through Jersey Client but in the same way I am getting 401-unauth error

Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358
Saurabh
  • 153
  • 12
  • Since it's not working in any of those cases: Is it possible, that you in fact are unauthorized or not using the correct authentication mechanism? – Oli Mar 21 '16 at 13:17
  • I check the same credential for Postman rest client and the API worked fine. I am not sure if I missed something – Saurabh Mar 22 '16 at 07:58
  • If you're using Postman you could use its "Generate Code" feature. It should be easy to find any missing headers (Accept, Content-Type) or differences in the URL. – Oli Mar 22 '16 at 08:28
  • Possible duplicate of [Connecting to remote URL which requires authentication using Java](http://stackoverflow.com/questions/496651/connecting-to-remote-url-which-requires-authentication-using-java) – Roman Vottner Mar 23 '16 at 15:17

0 Answers0