HowToRequestAHTTPWebServiceFromAXWikiPage

Version 1.1 by Jerome on 2008/09/24

Question How to request a HTTP Web Service from a XWiki Document
Answer

You can do this using the Groovy programming language. (You will need to have programming rights when saving the document).

Example : requesting the Twitter public time line in XML format

<%
   URL twitterURL;
        try {
            timelineURL = new URL("http://twitter.com/statuses/public_timeline.xml");
           
           def connection = timelineURL.openConnection();
           def text = connection.content.text

           // The following only prints the returned XML
           // in the wiki page as a "code" block.
           // You should replace it by your processing code to
           // exploit only the data relevant to you
           print ("{" + "code}\n")
           print text + "\n"
           print ("{" + "code}\n")
        }
       catch(Exception e) {print e.message}
%>

See http://java.sun.com/j2se/1.4.2/docs/api/java/net/HttpURLConnection.html for more information about possibilities of a HTTP connection.

Now if your Web Services requires authentication and support Basic Authentication, you can adapt from the following snippet, that does a POST request with credentials embed in a Authorization header, to post a status update on Twitter :

<%
      updateURL = new URL("http://twitter.com/statuses/update.xml");
           
     def connection = updateURL.openConnection();
           
      connection.setRequestProperty("Authorization", "Basic " +
(new sun.misc.BASE64Encoder().encode("username:password".getBytes())));
           
      connection.setDoOutput(true);
      connection.setRequestMethod("POST");

    def osr = new OutputStreamWriter(connection.getOutputStream());
     osr.write("status="+"Here the status you want to update");          
     osr.close();
    
    def responseText = connection.content.text
%>
Tags:
   

Get Connected