开发者

Requesting HTTPS URL

开发者 https://www.devze.com 2022-12-14 14:14 出处:网络
I am trying to grab some data from Delicious,开发者_开发百科 using URL class, URL url = URL(u);

I am trying to grab some data from Delicious,开发者_开发百科 using URL class,

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

open stream fails with 401,

url i am using is,

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

creds is a base64 encoded string e.g. user:pass encoded, i also tried non encoded form that fails also, can someone tell me what i am missing?


UPDATE: As pointed out below, the URL class does have some mechanism for handling user authentication. 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).

Modifying the code slightly, however, works just fine by specifying the Authorization header manually:

    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,

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


Rather use Apaches Commons libraries

0

精彩评论

暂无评论...
验证码 换一张
取 消