0

I am having some problems sending a POST request in java to a local server. I tested this local server with Postman and it is indeed working as it should. Sadly when i try sending the POST requst in java, everything goes as it should with 200 OK code, BUT there is nothing in the body. This is my code:

public static void request1() throws MalformedURLException, ProtocolException, IOException {                

    URL url = new URL("http://192.168.1.200");
    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();  
    System.out.println(httpCon.getResponseCode());
    System.out.println(httpCon.getResponseMessage());

}

EDIT: i see some of you said that this is a duplicate and gave me another link where it is supposed to be solved. Sadly i tried the code from that link and it is not working. Server simply says that the request has no body.

user3701179
  • 71
  • 1
  • 1
  • 5

2 Answers2

1

From the HttpUrlConnection#getResponseMessage JavaDoc:

Gets the HTTP response message, if any, returned along with the response code from a server.

From responses like:
HTTP/1.0 200 OK
HTTP/1.0 404 Not Found

Extracts the Strings "OK" and "Not Found"
respectively. Returns null if none could be discerned from the responses (the result was not valid HTTP).

If you want the response body, you need to extract it from the HttpUrlConnection InputStream.

You may use HttpUrlConnection#getInputStream.

LppEdd
  • 20,274
  • 11
  • 84
  • 139
0

For getting the actual response body you need to read it from,

httpCon.getInputStream()

You may read the data in a string with a one liner like this,

String responseBody = new BufferedReader(new InputStreamReader(httpCon.getInputStream())).lines().collect(
        Collectors.joining("\n"));
System.out.println(responseBody);
Pushpesh Kumar Rajwanshi
  • 18,127
  • 2
  • 19
  • 36