Calling Posterous API in Java

person sticking a post it on a white board with the words how to written on it

I was playing with Posterous API to call it in Java program. If you guys want to call Posterous API, you need to get API Token from Posterous API Docs first. This API Token (api_token) will go with every URL that you will invoke in your code.

I was missing this token and was wondering why I am getting HTTP 401 authentication failure. Well you can use following class to use Posterous API in Java.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;

public class AuthPosterous {
	private static BufferedReader data;

	  public static void authenticateHttpRequest(String webAddress, String username, String password) throws Exception {
	      Authenticator.setDefault(new MyAuthenticator(username, password));
	      URL url = new URL(webAddress);
	      URLConnection connection = url.openConnection();
	      data = new BufferedReader( new InputStreamReader(connection.getInputStream()) );
	  }

	  public static String readHttpRequest() throws Exception {
	      StringBuilder builder = new StringBuilder();
	      for (String line = null; (line = data.readLine()) != null;) {
	          builder.append(line).append("\n");
	      }
	      return builder.toString();
	  }

	  protected static class MyAuthenticator extends Authenticator {
	      private String username, password;
	      public MyAuthenticator(String user, String pwd) {
	          username = user;
	          password = pwd;
	      }
	      protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password.toCharArray()); }
	  }

	    public static void main (String arg[]){
	        try {
	        	String yourPosterousUsername= "<yourEmailAsUserName>", yourPassword = "<yourPassword>",
	        		theAPIURL="http://posterous.com/api/2/users/me?api_token=<get_API_Token_From_Posterous_Docs>";
	        	/* get your API token from http://posterous.com/api */
	            AuthPosterous.authenticateHttpRequest(theAPIURL, yourPosterousUsername,yourPassword);
	              String readData = AuthPosterous.readHttpRequest();
	              System.out.println(readData);
	            }catch (Exception e) {
	                e.printStackTrace();
	            }
	    }
	}

You May Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.