I am using HttpURLConnection
to make a POST request to a local service deployed locally and created using JAVA Spark. I want to send some data in request body when I make the POST call using the HttpURLConnection
but every time the request body in JAVA Spark is null. Below is the code I am using for this
Java Spark POST Service Handler
post("/", (req, res) -> {
System.out.println("Request Body: " + req.body());
return "Hello!!!!";
});
HTTPClass making the POST call
public class HTTPClassExample{
public static void main(String[] args) {
try{
URL url = new URL("http://localhost:4567/");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");
httpCon.connect();
OutputStream os = httpCon.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
osw.write("Just Some Text");
System.out.println(httpCon.getResponseCode());
System.out.println(httpCon.getResponseMessage());
osw.flush();
osw.close();
} catch(Exception ex){
ex.printStackTrace();
}
}
}
getOutputStream
callsconnect
under the covers. If you want to explicitly connect, callconnect
beforegetOutputStream
. To test yourself, disable your internet and when the connection fails, you'll seegetOutputStream
calledconnect
which failed. – Agenda