Quantcast
Channel: Languages – AMIS Technology Blog | Oracle – Microsoft Azure
Viewing all articles
Browse latest Browse all 163

Make HTTP POST request from Java SE – no frills, no libraries, just plain Java

$
0
0
Share this on .. Tweet about this on TwitterShare on LinkedInShare on FacebookShare on Google+Email this to someoneShare on TumblrBuffer this page

This article shows a very simple, straightforward example of making an HTTP POST call to a url (http://localhost:8080/movieevents) and sending a JSON payload to that URL.

The REST service invoked in this example is the service published from Java EE as described in this article.

package nl.amis.cinema.view;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import java.io.OutputStream;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;



public class CinemaEventGenerator  {
    /*
     * based on https://technology.amis.nl/2015/05/12/make-http-post-request-from-java-se-no-frills-no-libraries-just-plain-java/
     */

    private static final String USER_AGENT = "Mozilla/5.0";
    private static final String targeturl = "http://localhost:7101//CinemaMonitor/resources/cinemaevent";


public static void sendJson(String json) throws MalformedURLException, IOException {


        //method call for generating json

//        requestJson = generateJSON();
        URL myurl = new URL(targeturl);
        HttpURLConnection con = (HttpURLConnection)myurl.openConnection();
        con.setDoOutput(true);
        con.setDoInput(true);

        con.setRequestProperty("Content-Type", "application/json;");
        con.setRequestProperty("Accept", "application/json,text/plain");
        con.setRequestProperty("Method", "POST");
        OutputStream os = con.getOutputStream();
        os.write(json.toString().getBytes("UTF-8"));
        os.close();


        StringBuilder sb = new StringBuilder();
        int HttpResult =con.getResponseCode();
        if(HttpResult ==HttpURLConnection.HTTP_OK){
        BufferedReader br = new BufferedReader(new   InputStreamReader(con.getInputStream(),"utf-8"));

            String line = null;
            while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
            }
             br.close();
             System.out.println(""+sb.toString());

        }else{
            System.out.println(con.getResponseCode());
            System.out.println(con.getResponseMessage());
        }

    }


public static void main(String[] args) {
        try {
            CinemaEventGenerator.sendJson("{\"room\":\"4\" , \"occupation\":\"5\"}");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this second example, the service that is being called here is exposed by a PL/SQL procedure as described in this recent article). This example does not use any additional libraries – just the standard Java SE libraries.

package nl.amis.rest;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import java.io.Reader;

import java.io.UnsupportedEncodingException;

import java.net.HttpURLConnection;
import java.net.URL;

import java.net.URLEncoder;

import java.util.LinkedHashMap;
import java.util.Map;


public class CinemaEventRouter {
    /*
     * Thanks to: http://stackoverflow.com/questions/4205980/java-sending-http-parameters-via-post-method-easily?rq=1
     */

    private static final String USER_AGENT = "Mozilla/5.0";
    private static final String targeturl = "http://localhost:8080/api/movieevents";

    public static void sendPost(String json)  {
        try {
        Map<String, Object> params = new LinkedHashMap<>();
        params.put("p_json_payload", json);

        StringBuilder postData = new StringBuilder();
        for (Map.Entry<String, Object> param : params.entrySet()) {
            if (postData.length() != 0)
                postData.append('&');
            postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            postData.append('=');
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
        }
        byte[] postDataBytes = postData.toString().getBytes("UTF-8");


        URL url = new URL(targeturl);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
        conn.setDoOutput(true);
        conn.getOutputStream().write(postDataBytes);

        Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        for (int c; (c = in.read()) >= 0; System.out.print((char) c))
            ;
        }
        catch (Exception e) {
            System.out.println("Call to "+targeturl+" failed.");
            e.printStackTrace();
        }

    }
}
Share this on .. Tweet about this on TwitterShare on LinkedInShare on FacebookShare on Google+Email this to someoneShare on TumblrBuffer this page

The post Make HTTP POST request from Java SE – no frills, no libraries, just plain Java appeared first on AMIS Oracle and Java Blog.


Viewing all articles
Browse latest Browse all 163

Trending Articles