Skip to content

Instantly share code, notes, and snippets.

@julianazanelatto
Created November 18, 2021 23:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save julianazanelatto/bf70a9e858da0f7d1a836d1c9cf94103 to your computer and use it in GitHub Desktop.
Save julianazanelatto/bf70a9e858da0f7d1a836d1c9cf94103 to your computer and use it in GitHub Desktop.
post request example
package com.httpexamples;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Path;
import java.time.Duration;
public class postRequest {
public static final String URL_POST = "http://httpbin.org/forms/post";
public static final String FILE_JSON = "/home/jm/IdeaProjects/HttpExample/pedido.json";
public static void main(String[] args) throws IOException, InterruptedException {
// cliente HTTP
HttpClient client = HttpClient.newHttpClient();
// criar a requisição
HttpRequest request = HttpRequest.newBuilder()
.POST(HttpRequest.BodyPublishers.ofFile(Path.of(FILE_JSON)))
.timeout(Duration.ofSeconds(10))
.uri(URI.create(URL_POST))
.build();
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join();
System.out.println(request.bodyPublisher());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment