RemoteService a simple client to test your Restful and SOAP services PDF Print E-mail
Written by T.A. Nguyen   
Wednesday, 11 May 2011 13:24

Random thought...

As Java growth, so does the Web Service spaces along with the complexity of the services it can handle.  With Axis/Axis2 then come along CXF many of these implementation are wonderful in focusing on how to make it easier for developer to create webservices.  I am all for it, and thankful for those who contribute to make it better.  SoapUI a recent addition to the slewth of tool that help with the web-services space, great tool, a must check and use if you use web services day in day out.

As an educator, I often being asked about the basic building block behind these.  One of my favorist is the simple http/https implementation.  Yes, it all started when the world wild web protocol started....

So, I find myself refer back to my basic http/s get/post code that had been develop a decade ago... and amazingly, it still work, not only that it also serve as great example for my student to understanding the building block behind it all.

 

Here are my 2 simple classes that I been using for a while:

 

// RemoteService 
package org.cnci.service.util.client;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

// There are several flavors of these 
import org.apache.axis.encoding.Base64;

/**
 * provide as is, no warranty.
 * @author T.A. Nguyen
 * ta{at}cnci{dot}org
 */
public class RemoteService {

   /**
    * Simple remote get/post client if data present, it will do a post, if user
    * present it will place it in the Authorization header
    * 
    * @throws RemoteServiceException
    **/
   public static String postService(String url, String data, String user) 
      throws RemoteServiceException 
   {
      return remoteService(url, data, user, null, null);
   }

   public static String getService(String getUrl, String user, 
                 String password, String encoding) throws RemoteServiceException 
   {
      return remoteService(getUrl, null, user, password, encoding);
   }

   public static String getService(String getUrl, String user) 
           throws RemoteServiceException 
   {
      return remoteService(getUrl, null, user, null, null);
   }

   public static String remoteService(String getUrl, String data, String user, 
      String password, String encoding) throws RemoteServiceException 
   {
      OutputStreamWriter wr = null;
      BufferedReader rd = null;
      String result = null;

      try {
         StringBuffer buff = new StringBuffer();
         URL url = new URL(getUrl);
         URLConnection uc = url.openConnection();
         uc.setRequestProperty("User-Agent", "TAzilla/4.0");
         
         /* ----- encoding, we use "identity" for authentication -------
          * Accept-Encoding: compress, gzip
          * Accept-Encoding:
          * Accept-Encoding: *
          * Accept-Encoding: compress;q=0.5, gzip;q=1.0
          * Accept-Encoding: gzip;q=1.0, identity; q=0.5, *;q=0
          */
         if (encoding == null) encoding = "identity";
         uc.setRequestProperty("Accept-Encoding", encoding);
         if (user != null) {
            String auth = user;
            if (password != null) {
               String encode = user + ":" + password;
               auth = "Basic " + Base64.encode(encode.getBytes());
            }
            uc.setRequestProperty("Authorization", auth);
         }
         if (data != null) {
            uc.setDoOutput(true);
            wr = new OutputStreamWriter(uc.getOutputStream());
            wr.write(data);
            wr.flush();
         }

         // Get the response
         rd = new BufferedReader(new InputStreamReader(uc.getInputStream()));
         String line=null;
         while ((line = rd.readLine()) != null) {
            buff.append(line + "\n");
         }
         result = buff.toString();

         if (result.indexOf("Exception: ") > 0) {
            throw new RemoteServiceException(result);
         }
      } catch (Exception e) {
         throw new RemoteServiceException(e.getMessage(), e);
      } finally {
         try {
            if (wr != null) wr.close();
            if (rd != null) rd.close();
         } catch (Exception e) {
            e.printStackTrace();
         }
      }

      return result;
   }

   /**
    * test codes.... 
    * @param args
    */
   public static void main(String[] args) {
      try {
         String url = "http://localhost:9000/service/MyRestfulService?getPerson=5";
         String data = remoteService(url, null, "myUserId", "secret", "identity");
         System.out.println("data:>>" + data);
      } catch (RemoteServiceException e) {
         e.printStackTrace();
      }
   }
}


// RemoteServiceException 
package org.cnci.service.util.client;

/**
 * provide as is, no warranty.
 * @author T.A. Nguyen
 * ta{at}cnci{dot}org
 */
public class RemoteServiceException extends Exception {
   private static final long serialVersionUID = 1L;

   public RemoteServiceException() {
   }

   public RemoteServiceException(String msg) {
      super(msg);
   }

   public RemoteServiceException(Throwable e) {
      super(e);
   }

   public RemoteServiceException(String msg, Throwable e) {
      super(msg, e);
   }
}

And as many of the https protocol, there are invalid/expired certs that show up more often that us developers like to see. The problem is a valid certificate cost yearly fee, not sure why? And so to enable the security cost, most of the smaller (mom and pop) web sites and services just use the default or expired certs, this cause the problem to the Java space of end up enforcing to a failed certificate. Sun, provided a neat tool called InstallCert.java by Sun Micro System. Just download and follow these steps

  • javac InstallCert.java
  • java InstallCert yoursslserver:sslport

For a full solution refer to Sthyo blogs.

Bookmark with:

Deli.cio.us    Digg    reddit    Facebook    StumbleUpon    Newsvine
Comments (0)
Write comment
Your Contact Details:
Gravatar enabled
Comment:
[b] [i] [u] [url] [quote] [code] [img]   
:D:angry::angry-red::evil::idea::love::x:no-comments::ooo::pirate::?::(:sleep::););)):0
Security
Please input the anti-spam code that you can read in the image.
Last Updated on Friday, 27 April 2012 01:55
 
T.A. Nguyen, Powered by Joomla! and VNSAB.com