Calling Posterous API in Java

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.


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;) {
	      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>",
	        	/* get your API token from */
	            AuthPosterous.authenticateHttpRequest(theAPIURL, yourPosterousUsername,yourPassword);
	              String readData = AuthPosterous.readHttpRequest();
	            }catch (Exception e) {
Related Posts Plugin for WordPress, Blogger...

Leave a Reply

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