如何在java中访问https站点

时间:2011-01-21 05:17:23

标签: java https httpurlconnection

我必须通过我的java代码访问https网站。但它返回401响应。我在下面提供了我的代码。

try {        
 URL u = new URL(url);
 HttpURLConnection http = (HttpURLConnection)u.openConnection();
 http.setAllowUserInteraction(true);
 http.connect();

 String userpassword = "HP:M0lveau";
 byte[] encoded = Base64.encodeBase64(userpassword.getBytes());
 String encodedAuthorization = new String(encoded);

 http.setRequestProperty("Authorization", "Basic " + encodedAuthorization);
 InputStream is = http.getInputStream();

 BufferedReader reader = new BufferedReader(new InputStreamReader(is));
 StringBuilder stringBuilder = new StringBuilder();
 String line = null;
 while ((line = reader.readLine()) != null) {
   stringBuilder.append(line + "\n");
 }
 return stringBuilder.toString();

} catch (IOException ioe) {
 logger.debug("fetchDataFromServer:IOException");
 return null;
}

请尽早帮助..提前致谢....

3 个答案:

答案 0 :(得分:2)

401响应表示请求需要用户身份验证。看here for help

有像

这样的东西
public static String userNamePasswordBase64(String username, String password)
{
    return "Basic " + base64Encode (username + ":" + password);
}

static public String base64Encode(String s)
{
    ByteArrayOutputStream bout = new ByteArrayOutputStream();

    Base64OutputStream out = new Base64OutputStream(bout);
    try
    {
        out.write(s.getBytes());
        out.flush();
    } catch (IOException e)
    {
    }
return bout.toString();
}

然后使用

http.setRequestProperty ("Authorization",userNamePasswordBase64("HP","M01veau"));
http.connect();

同时手动检查这些凭据在给定的URL上是否正常工作。 另外See this great tutorial

答案 1 :(得分:2)

尝试在调用connect()

之前设置Authorization标头

答案 2 :(得分:2)

我明白了..这是我的代码。

private static String fetchDataFromServer() throws HttpException, IOException, NoSuchAlgorithmException, KeyManagementException {

        logger.trace("__ENTERING CluemasterData::fetchDataFromServer()");

        try {
            URL u = new URL("https://....");
            HttpsURLConnection http = (HttpsURLConnection)u.openConnection();
            Authenticator.setDefault( new MyAuthenticator() );
            http.setAllowUserInteraction(true);
            http.setRequestMethod("GET");
            http.connect();

            InputStream is = http.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder stringBuilder = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null)
            {
                stringBuilder.append(line + "\n");
            }
            return stringBuilder.toString();    
        }
        catch (HttpException he) {

            return null;
        } 
        catch (IOException ioe) {

            return null;
        }

    }

MyAuthenticator类

import java.net.Authenticator;
import java.net.PasswordAuthentication;

class MyAuthenticator extends Authenticator
   {
   /**
   * Called when password authorization is needed.
   * @return The PasswordAuthentication collected from the
   * user, or null if none is provided.
   */
   protected PasswordAuthentication getPasswordAuthentication()
      {
      return new PasswordAuthentication ( "username", "password".toCharArray() );
      }
   }