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

Lucas Jellema 1

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 params = new LinkedHashMap<>();
params.put(“p_json_payload”, json);

StringBuilder postData = new StringBuilder();
for (Map.Entry 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();
}

}
}

One thought on “Make HTTP POST request from Java SE – no frills, no libraries, just plain Java

  1. con.setRequestProperty(“Content-Type”, “application/json;”); this line should be corrected as con.setRequestProperty(“Content-Type”, “application/json”); There’s an additional “;” after “application/json”

Comments are closed.

Next Post

Use the inbound REST adapter of StreamExplorer to consume events from HTTP POST requests

Facebook0TwitterLinkedinStreamExplorer is a fairly recent product from Oracle – a business user friendly layer around Oracle Event Processor. In various previous articles, I have discussed StreamExplorer. I have demonstrated how SX can consume events from JMS, EDN and from CSV files. This article shows how a stream in StreamExplorer can […]