Connecting to remote URL which requires authentication using Java

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

    As i have came here looking for an Android-Java-Answer i am going to do a short summary:

    1. Use java.net.Authenticator as shown by James van Huis
    2. Use Apache Commons HTTP Client, as in this Answer
    3. Use basic java.net.URLConnection and set the Authentication-Header manually like shown here

    If you want to use java.net.URLConnection with Basic Authentication in Android try this code:

    URL url = new URL("http://www.mywebsite.com/resource");
    URLConnection urlConnection = url.openConnection();
    String header = "Basic " + new String(android.util.Base64.encode("user:pass".getBytes(), android.util.Base64.NO_WRAP));
    urlConnection.addRequestProperty("Authorization", header);
    // go on setting more request headers, reading the response, etc
    

提交回复
热议问题