Connecting to remote URL which requires authentication using Java

前端 未结 12 2187
庸人自扰
庸人自扰 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条回答
  •  -上瘾入骨i
    2020-11-22 13:50

    If you are using the normal login whilst entering the username and password between the protocol and the domain this is simpler. It also works with and without login.

    Sample Url: http://user:pass@domain.com/url

    URL url = new URL("http://user:pass@domain.com/url");
    URLConnection urlConnection = url.openConnection();
    
    if (url.getUserInfo() != null) {
        String basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
        urlConnection.setRequestProperty("Authorization", basicAuth);
    }
    
    InputStream inputStream = urlConnection.getInputStream();
    

    Please note in the comment, from valerybodak, below how it is done in an Android development environment.

提交回复
热议问题