How to handle HTTP authentication using HttpURLConnection?

前端 未结 2 490
忘掉有多难
忘掉有多难 2020-11-28 09:49

I\'m writing a Java client that POSTs to a HTTP server that requires authentication.
I have to support at least the following three authentication metho

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-28 10:32

    Do you need output streaming? The HttpURLConnection most definitely supports authentication with the Authenticator class, see: Http Authentication.

    Update: In case the Authenticator is not an option, you can manually do HTTP basic authentication by adding an extra header to your HTTP request. Try the following code (untested):

    String userPassword = username + ":" + password;
    String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes());
    URLConnection uc = url.openConnection();
    uc.setRequestProperty("Authorization", "Basic " + encoding);
    uc.connect();
    

提交回复
热议问题