0

I have a simple Java servlet running on Tomcat at http://localhost:8081/myApp

I am trying to send a HTTP POST request to this from a test harness in a main method.

Currently I am printing out the method and headers on the servlet. What's weird is that even though I set the connection method to POST, on the servlet it's GET. Also, other headers are missing or not what I set them too.

However, if I use https://postman-echo.com/post as the URL instead of http://localhost:8081/myApp it works as expected. That is, I get a response code of 200 and an echo back of my json body.

What's being printed out on my servlet:

Method: GET

Header Name: user-agent Value: Java/1.8.0_191

Header Name: host Value: localhost:8081

Header Name: accept, Value: text/html, image/gif, image/jpeg, *; q=.2, /; q=.2

Header Name: connection Value: keep-alive

There has to be something I am missing here.

public static void main(String[] args) {

    //String ENDPOINT_URL = "http://localhost:8081/myApp";
    String ENDPOINT_URL = "https://postman-echo.com/post";

    String json = "{\"foo\":\"bar\"}";

    System.out.println(json);

    //open connection
    try {
        URL url = new URL(ENDPOINT_URL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST"); //set to POST method
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setAllowUserInteraction(false);

        conn.setRequestProperty ("Content-type", "application/json"); //json
        conn.setRequestProperty("Accept", "application/json");

        //send the request
        BufferedWriter reqWriter = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
        reqWriter.write(json);
        reqWriter.close();

        int responseCode = conn.getResponseCode();
        System.out.println(responseCode);

        InputStream response = conn.getInputStream();
        BufferedReader in   =
            new BufferedReader (new InputStreamReader (response));
        String line;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }
        in.close();



    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();        
    } catch (ProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }



}
  • [this](https://stackoverflow.com/questions/3324717/sending-http-post-request-in-java) might help you – Swati Apr 27 '19 at 04:08

1 Answers1

0

The method conn.setDoOutput(true) actually triggers conn.connect(). and after connect() was invoked, setting request properties has no effect. Try moving the statement to a place after you set all your request properties.