简体   繁体   中英

Cannot access web page with credentials from java

I'm accessing RabbitMQ Queue information from java code.

    public class NewClass {
    private static Object Base64Converter;
    public static void main(String args[])
    {
            try {

                String credentials = "test" + ":" + "test";
                String encoding = base64Encode(credentials);
                URL url = new URL("http://192.168.0.30:15672/api/queues");
                URLConnection uc = url.openConnection();
                uc.setRequestProperty("Authorization", String.format("Basic %s", encoding));

            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String inputLine; 

            while ((inputLine = in.readLine()) != null) {
                // Process each line.
                System.out.println(inputLine);
            }
            in.close(); 

        } catch (MalformedURLException me) {
            System.out.println(me); 

        } catch (IOException ioe) {
            System.out.println(ioe);
        }
    }
  private static String base64Encode(String stringToEncode)
  {
    return DatatypeConverter.printBase64Binary(stringToEncode.getBytes());
  }

java.io.IOException: Server returned HTTP response code: 401 for URL: http://192.168.0.30:15672/api/queues

You prepare a URLConnection with proper authentication but then you don't use it when you call url.openStream() . This should work:

 ...
 URLConnection uc = url.openConnection();
 uc.setRequestProperty("Authorization", String.format("Basic %s", encoding));
 uc.connect();
 BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));

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