Research Log of Web Science Students

Computer Science is not simply programming

My first dip at Web Services

leave a comment »

Yesterday I found myself delving into my first foray into the whole new world of web services when I was helping Kee(a .NET person) connect to DivShare for the upload feature in their web app using Java.

I have thought about making my own framework in Java for URL rewriting because I knew I would need it someday to make API calls but what I didn’t know was a class like this already exists in the Java SDK.

To call a web service first determine:

1. The url where the web service will get requests
2. The parameters the web service requires

From there, it’s a matter of making a post request by forming the parameters that the web service needs.

To form the parameters for call to a web service means forming a URL (given by the web service) with the parameters right after. Ever noticed how some URLs can be so long?

long_url

The parameters are written into the url by attribute value pairs as in the picture above:

service=ah
continue=https://appengine.google.com/_ah/login/

To do this in Java, use URLEncoder’s encode method:

String data = URLEncoder.encode("service", "UTF-8") 
            + "=" + URLEncoder.encode("ah", "UTF-8");

data += "&" + URLEncoder.encode("continue", "UTF-8") + 
        "=" + URLEncoder.encode("https://appengine.google.com/_ah/login/", "UTF-8");

Making a post request is done like this:

 URL url = new URL("http://hostname:80/cgi");
 URLConnection conn = url.openConnection();
 conn.setDoOutput(true);
 OutputStreamWriter wr = 
         new OutputStreamWriter(conn.getOutputStream());
 wr.write(data);
 wr.flush();
    
 // Get the response
BufferedReader rd = new BufferedReader(new
       InputStreamReader(conn.getInputStream()));

String line;
while ((line = rd.readLine()) != null) {
    // Process line...
}
wr.close();
rd.close();

Some more tutorials I found here

Advertisements

Written by Jose Asuncion

October 2, 2009 at 4:48 am

Posted in Hardwire

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: