vendredi 22 mars 2013

Envoi d'une requête POST sur Google App Engine


Pour envoyer une requête POST sur Google App Engine, vous avez besoin d'utiliser le service Google : Url Fetch service. "The URL Fetch service uses Google's network infrastructure for efficiency and scaling purposes".

Voici un exemple très simple :

   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());
        }
    }

J'ai fait un petit projet jave ( 2 class ;-) ) qui envoi une requête POST :  https://github.com/drieu/Tools
Plus de détails sur https://developers.google.com/appengine/docs/java/urlfetch/overview