Friday, March 22, 2013

Send a POST request on Google App Engine

To send a request, you need to use Url Fetch service.The URL Fetch service uses Google's network infrastructure for efficiency and scaling purposes.Here is the code to send a simple POST request on Google App Engine :

   public void send(String messageToSend, String date, String level, String servers) {

        try {
            String message = URLEncoder.encode(messageToSend, ENCODING);
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyUrl, Integer.parseInt(proxyPort)));

            URL url = new URL(urlDest);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");

            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            writer.write("date=" + date);
            writer.write("&level=" + level);
            writer.write("&servers=" + servers);
            writer.write("&msg=" + message);
            writer.close();

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                logger.info("OK ! message returned:" + connection.getResponseCode());
            } else {
                logger.info("KO ! message returned:" + connection.getResponseCode());
            }
        } catch (MalformedURLException e) {
            logger.error(e.getMessage());
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    }

I've made a small java project ( 2 class ;-) )that send a simple POST request : See https://github.com/drieu/Tools
More details on https://developers.google.com/appengine/docs/java/urlfetch/overview