Connecting to remote URL which requires authentication using Java

前端 未结 12 2202
庸人自扰
庸人自扰 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:37

    Use this code for basic authentication.

    URL url = new URL(path);
    String userPass = "username:password";
    String basicAuth = "Basic " + Base64.encodeToString(userPass.getBytes(), Base64.DEFAULT);//or
    //String basicAuth = "Basic " + new String(Base64.encode(userPass.getBytes(), Base64.No_WRAP));
    HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
    urlConnection.setRequestProperty("Authorization", basicAuth);
    urlConnection.connect();

提交回复
热议问题