HTTP POST using JSON in Java

前端 未结 11 1210
南笙
南笙 2020-11-22 07:24

I would like to make a simple HTTP POST using JSON in Java.

Let\'s say the URL is www.site.com

and it takes in the value {\"name\":\"mynam

11条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 08:10

    For Java 11 you can use new HTTP client:

     HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("http://localhost/api"))
            .header("Content-Type", "application/json")
            .POST(ofInputStream(() -> getClass().getResourceAsStream(
                "/some-data.json")))
            .build();
    
        client.sendAsync(request, BodyHandlers.ofString())
            .thenApply(HttpResponse::body)
            .thenAccept(System.out::println)
            .join();
    

    You can use publisher from InputStream, String, File. Converting JSON to the String or IS you can with Jackson.

提交回复
热议问题