java访问https网站的方法

发布于 2024-10-13 03:41:45 字数 900 浏览 4 评论 0原文

我必须通过我的 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;
}

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

I have to access an https site through my java code. But it returns 401 response. I included my code below.

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;
}

Please help as early as possible.. Thanks in advance....

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

生活了然无味 2024-10-20 03:41:45

尝试在调用 connect() 之前设置授权标头

Try to set the Authorization header before the call to connect()

殤城〤 2024-10-20 03:41:45

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

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() );
      }
   }

I got it.. This is my code.

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;
        }

    }

The class 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() );
      }
   }
本宫微胖 2024-10-20 03:41:45

401响应表示该请求需要用户身份验证。查看此处寻求帮助

有类似

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 上是否正常工作。
另外查看这个很棒的教程

401 response means that the request requires user authentication. LOOK here for help

Have something like

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();
}

and then use

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

Also check manually that these credentials are working fine on the given url.
Also See this great tutorial

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文