1
curl -X POST --header "Content-Type: text/plain" --header "Accept: application/json" -d "HELLO THERE" "http://localhost:8080/rest/items/Echo_Living_Room_TTS"

I want to write Java code that does the same thing as this curl invocation. Here's what I've written so far:

URL myurl =new URL("http://localhost:8080/rest/items/Echo_Living_Room_TTS");
HttpURLConnection connection = (HttpURLConnection) myurl.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type","text/plain");
connection.connect();
String urlParameters  = "HELLO THERE";
byte[] postData       = urlParameters.getBytes( StandardCharsets.UTF_8 );
if(something happens) {
    try( DataOutputStream wr = new DataOutputStream( connection.getOutputStream())) {
        wr.write( postData );
    }
}
connection.disconnect();

Have I done it right? Are there any mistakes or omissions?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Mexar_
  • 11
  • 1
  • why don't you use spring boot? are you looking at only in core Java? – prostý člověk Nov 26 '20 at 07:43
  • See this if it helps: https://stackoverflow.com/questions/3324717/sending-http-post-request-in-java – KnockingHeads Nov 26 '20 at 07:43
  • What is *"if(something happens)"*? I sure hope that's not a check of the *response* status, because how do you think you can get the response status *before* you send the *request* body? --- Why do you wrapper the `OutputStream` in a `DataOutputStream`? – Andreas Nov 26 '20 at 07:52
  • `something happens` is just a variable from another class, now I try to change the DataOutputStream into OutpuStream – Mexar_ Nov 26 '20 at 07:59

1 Answers1

0

Ok seems like I made it works:

        URL myurl =new URL("http://localhost:8080/rest/items/Echo_Living_Room_TTS");
        HttpURLConnection connection = (HttpURLConnection) myurl.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type","text/plain");
        connection.setRequestProperty("Accept","application/json");
        String mystring  = "whatever";
        byte[] postData       = mystring.getBytes( StandardCharsets.UTF_8 );
        int lenght = postData.length;
        connection.setFixedLengthStreamingMode(lenght);
        connection.connect();
        try(OutputStream os = connection.getOutputStream()) {
            os.write( postData );
        }
        connection.disconnect();

thank you all

Mexar_
  • 11
  • 1