Receiving null Value while using POST method in servlet?

Copy pasted your code in my servlet worked fine

  1. Check that you overrided doPost method in the servlet

  2. Check that you that your post metod work fine and return value, I use “DHC Rest Client” plugin for chrome. It is very cool tool

  3. Try to remove httpCon.connect() line. It is not necessary.

    From oracle docs about connect() method:

Operations that depend on being connected, like getContentLength, will
implicitly perform the connection, if necessary.

Operations getResponseMessage, getResponseCode perform the connection.

UPDATED

I tried to test with my local test url and it works. Then i tried with your url and it does not work.

You need to flush output stream before use input stream.

This code work and return “0#5#26#Temperature#Living_Room#555555581#0+0#7#0#Room1#Master_bedroom#555555581#1+1#7#0#Door1#Living_Room#555555581#2+1#6#0#frontdoor#Living_Room#555555581#2+0#6#0#doorback#Balcony#555555581#2+”

PrintWriter writer = res.getWriter();
String content = "10 141 nahush123 01";
URL url = new URL("https://52.220.37.12:8080/servers/servers");
System.out.println(url.toString());
HttpURLConnection httpCon = (HttpURLConnection)url.openConnection();
httpCon.setDoInput(true);
httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");
httpCon.setRequestProperty("Content-Type", "text/plain;charset=UTF-8");

OutputStream os = httpCon.getOutputStream();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(os));
out.write(content);
out.flush();
//br = BufferReader(out);
System.out.println(httpCon.getResponseCode());
System.out.println(httpCon.getResponseMessage());
writer.println(httpCon.getResponseMessage());


//httpCon.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
//reading response
//String resp;
//if(br != null){
content = br.readLine();
//}
System.out.println(content);
writer.println(content);
writer.flush();
writer.close();
out.close();
os.close();

Leave a Comment