javahttppost请求代码等价于curl调用

rdrgkggo  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(360)
curl -X POST --header "Content-Type: text/plain" --header "Accept: application/json" -d "HELLO THERE" "http://localhost:8080/rest/items/Echo_Living_Room_TTS"

我想编写与curl调用相同的java代码。以下是我迄今为止写的:

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();

我做对了吗?是否有任何错误或遗漏?

ev7lccsx

ev7lccsx1#

好吧,看来我成功了:

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();

谢谢大家

相关问题