IT Certificaions

Google Cloud Platform

Tuesday, December 24, 2013

Send POST request with JSON data on Google App Engine

Tag: Fusion Table Rest API, Send POST request with JSON data on Google App Engine

1) Create fusion table using post request on Google App Engine

// postURL= "https://www.googleapis.com/fusiontables/v1/tables?access_token=**********"
// access_token - Use Oauth2 for this

public static String sendPostRequest(String postURL) throws Exception{
        String responseStr=null;
        //make POST request
        String jsonContent = "{'name': 'newIndia','columns': [{'name': 'Species','type': 'STRING'}],'description': 'Insect Tracking Information.','isExportable': true}";
        //String data = "{\"document\" : {\"_id\": \"" + id+ "\", \"context\":" + context +"}}";
        URL url = new URL(postURL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("charset", "utf-8");
        connection.setRequestProperty("Content-Length", "" + Integer.toString(jsonContent.getBytes().length));
        connection.setUseCaches(false);

        OutputStreamWriter  writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        writer.write(jsonContent);       
        writer.close();
        responseStr="Response code: "+connection.getResponseCode()+" and mesg:"+connection.getResponseMessage();
       
        System.out.println(connection.getResponseMessage());
       
       
        InputStream response;                  

        // Check for error , if none store response
        if(connection.getResponseCode() == 200){
            response = connection.getInputStream();
        }else{
            response = connection.getErrorStream();
        }
        InputStreamReader isr = new InputStreamReader(response);
        StringBuilder sb = new StringBuilder();
        BufferedReader br = new BufferedReader(isr);
        String read = br.readLine();
        while(read != null){
            sb.append(read);
            read = br.readLine();
        }  
        // Print the String    
        System.out.println(sb.toString());
       
        connection.disconnect();
        return responseStr;
    }