简体   繁体   English

请求HTTPS URL

[英]Requesting HTTPS URL

I am trying to grab some data from Delicious, using URL class, 我正在尝试使用URL类从Delicious抓取一些数据,

URL url = URL(u); 
url.openStream();

open stream fails with 401, 打开流失败并显示401,

url i am using is, 我使用的网址是

String("https://" + creds + "@api.del.icio.us/v1/posts/recent"); String(“ https://” +凭据+“ @ api.del.icio.us / v1 / posts / recent”);

creds is a base64 encoded string eg user:pass encoded, i also tried non encoded form that fails also, can someone tell me what i am missing? creds是base64编码的字符串,例如user:pass编码,我也尝试了非编码形式,但也失败了,有人可以告诉我我所缺少的吗?

UPDATE: As pointed out below, the URL class does have some mechanism for handling user authentication. 更新:正如下面所指出的,URL类确实具有一些用于处理用户身份验证的机制。 However, the OP is correct that the del.icio.us service returns a 401 using code as shown above (verified with my own account, and I am providing the correct credentials .. sending them in the url unencoded). 但是,OP是正确的,因为del.icio.us服务使用上面显示的代码返回了401(已通过我自己的帐户验证,并且我提供了正确的凭据..以未编码的形式发送它们)。

Modifying the code slightly, however, works just fine by specifying the Authorization header manually: 但是,通过手动指定Authorization标头,稍微修改代码即可正常工作:

    URL url = new URL("https://api.del.icio.us/v1/posts/suggest");
    byte[] b64 = Base64.encodeBase64("username:pass".getBytes());
    URLConnection conn = url.openConnection();
    conn.setRequestProperty("Authorization", "Basic " + new String(b64));
    BufferedReader r = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    while(r.ready()){
        System.out.println(r.readLine());
    }

You need to provide a password authenticator like this, 您需要提供这样的密码验证器,

           Authenticator.setDefault( new Authenticator()
            {
              @Override protected PasswordAuthentication getPasswordAuthentication()
              {
                    return new PasswordAuthentication(username, 
                            password.toCharArray()
                            );
              }
            } );

However, this will add a round-trip because it has to wait for 401. You can set authentication header preemptively like this, 但是,这将增加往返行程,因为它必须等待401。您可以像这样预先设置身份验证标头,

        String credential = username + ":" + password;
        String basicAuth = "Basic " + 
                Base64.encode(credential.getBytes("UTF-8"));
        urlConnection.setRequestProperty("Authorization", basicAuth);

而是使用Apaches Commons

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM