tags:

views:

81

answers:

3

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?

A: 

Rather use Apaches Commons libraries

Trick
+3  A: 

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());
 }
BryanD
yes the problem is with delicious, if you have a new account you need to use v2 of their api thats why the call failed.
Hamza Yerlikaya
+1  A: 

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);
ZZ Coder