Send data in Request body using HttpURLConnection

utkarsh31 :

I am using HttpURLConnection to make a POST request to a local service deployed in my local 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();
        }
    }
}`
Ricardo :

You should call httpCon.connect(); only after you write your parameters in the body and not before. Your code should look like this:

URL url = new URL("http://localhost:4567/");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");
OutputStream os = httpCon.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");    
osw.write("Just Some Text");
osw.flush();
osw.close();
os.close();  //don't forget to close the OutputStream
httpCon.connect();

//read the inputstream and print it
String result;
BufferedInputStream bis = new BufferedInputStream(httpCon.getInputStream());
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result2 = bis.read();
while(result2 != -1) {
    buf.write((byte) result2);
    result2 = bis.read();
}
result = buf.toString();
System.out.println(result);

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=431891&siteId=1