Connecting to remote URL which requires authentication using Java

前端 未结 12 2201
庸人自扰
庸人自扰 2020-11-22 12:59

How do I connect to a remote URL in Java which requires authentication. I\'m trying to find a way to modify the following code to be able to programatically provide a userna

12条回答
  •  日久生厌
    2020-11-22 13:34

    You can also use the following, which does not require using external packages:

    URL url = new URL(“location address”);
    URLConnection uc = url.openConnection();
    
    String userpass = username + ":" + password;
    String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());
    
    uc.setRequestProperty ("Authorization", basicAuth);
    InputStream in = uc.getInputStream();
    

提交回复
热议问题