GHads mind

developers thoughts & finds

Calling a REST WebService from Java (without libs)

with 3 comments

I needed to geocode an address today by using free WebServices. The final solution is to use yahoo, but here is the full list of other usefull services:

Anyway, still needed to call the WS from Java, but thanks to google I found a solution quickly (http://xml.nig.ac.jp/tutorial/rest/index.html) and expanded it to my usecase:

    private static String buildWebQuery(Map<String, String> parameters) throws Exception {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : parameters.entrySet()) {
            String key = URLEncoder.encode(entry.getKey(), "UTF-8");
            String value = URLEncoder.encode(entry.getValue(), "UTF-8");
            sb.append(key).append("=").append(value).append("&");
        }
        return sb.toString().substring(0, sb.length() - 1);
    }

    public static String callRestfulWebService(String address, Map<String, String> parameters) throws Exception {
        return callRestfulWebService(address, parameters, null, 0);
    }

    public static String callRestfulWebService(String address, Map<String, String> parameters, String proxy, String port) throws Exception {
        return callRestfulWebService(address, parameters, proxy, Integer.parseInt(port));
    }

    public static String callRestfulWebService(String address, Map<String, String> parameters, String proxy, int port) throws Exception {

        Proxy proxyObject = null;
        if (StringUtils.isNotBlank(proxy) && port > 0) {
            InetSocketAddress proxyAddress = new InetSocketAddress(proxy, port);
            proxyObject = new Proxy(Proxy.Type.HTTP, proxyAddress);
        }

        String response = "";
        String query = buildWebQuery(parameters);

        // More info: http://xml.nig.ac.jp/tutorial/rest/index.html
        URL url = new URL(address);

        // make post mode connection
        URLConnection urlc = null;
        if (proxyObject == null) {
            urlc = url.openConnection();
        } else {
            urlc = url.openConnection(proxyObject);
        }
        urlc.setDoOutput(true);
        urlc.setAllowUserInteraction(false);

        // send query
        PrintStream ps = new PrintStream(urlc.getOutputStream());
        ps.print(query);
        ps.close();

        // retrieve result
        BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream(), "UTF-8"));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
            sb.append("\n");
        }
        br.close();
        response = sb.toString();

        return response;
    }

With these few methods you can call any REST WebService with any parameters (as Map) and use a proxy per call. The code also takes care of right encoding of parameters. The result is a xml string, which can be processed by regexp in an easy way.

Greetz, GHad

BTW: For how to create REST webservices take a look at: http://inverse2.com/?p=43

About these ads

Written by ghads

September 24, 2008 at 2:31 pm

Posted in Java development

Tagged with , ,

3 Responses

Subscribe to comments with RSS.

  1. [...] Calling a REST WebService from Java (without libs) « GHads mind @surya_s @davetron5000 Simple python often far simpler eg. http://goo.gl/7hx8i Also see http://goo.gl/IPyHY and http://goo.gl/HY0Lk (tags: via:packrati.us) [...]

  2. Doesn’t the code above requires some lib for StringUtils?

    --marc

    July 3, 2012 at 3:51 am

    • StringUtils was my own Lib at this times… It’s only used to check blankness which can be done without libs.

      ghads

      August 19, 2013 at 3:07 pm


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

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: