java.net.http.HttpRequest.BodyPublishers Java Examples

The following examples show how to use java.net.http.HttpRequest.BodyPublishers. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: R2ServerClient.java    From r2cloud with Apache License 2.0 8 votes vote down vote up
private void upload(String url, File file, String contentType) {
	HttpRequest request;
	try {
		request = createRequest(url).header("Content-Type", contentType).PUT(BodyPublishers.ofFile(file.toPath())).build();
	} catch (FileNotFoundException e) {
		LOG.error("unable to upload: {}", url, e);
		return;
	}
	httpclient.sendAsync(request, BodyHandlers.ofString()).exceptionally(ex -> {
		Util.logIOException(LOG, "unable to upload: " + url, ex);
		return null;
	}).thenAccept(response -> {
		if (response != null && response.statusCode() != 200 && LOG.isErrorEnabled()) {
			LOG.error("unable to upload: {} response code: {}. response: {}", url, response.statusCode(), response.body());
		}
	});
}
 
Example #2
Source File: ViaBody.java    From Java-Coding-Problems with MIT License 6 votes vote down vote up
public void bodyExample() throws IOException, InterruptedException {
    
    HttpClient client = HttpClient.newHttpClient();

    HttpRequest request = HttpRequest.newBuilder()
            .header("Content-Type", "application/json")
            .POST(BodyPublishers.ofString(
                    "{\"email\":\"[email protected]\",\"password\":\"cityslicka\"}"))
            .uri(URI.create("https://reqres.in/api/login"))
            .build();

    HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

    System.out.println("Status code: " + response.statusCode());
    System.out.println("\n Body: " + response.body());
}
 
Example #3
Source File: HttpClientDemo.java    From Learn-Java-12-Programming with MIT License 6 votes vote down vote up
private static void postAsync(){
    HttpClient httpClient = HttpClient.newHttpClient();

    HttpRequest req = HttpRequest.newBuilder()
            .uri(URI.create("http://localhost:3333/something"))
            .POST(BodyPublishers.ofString("Hi there!"))
            .build();

    CompletableFuture<String> cf =
            httpClient.sendAsync(req, BodyHandlers.ofString())
                    .thenApply(resp -> "Server responded: " + resp.body());
    System.out.println("The request was sent asynchronously...");
    try {
        System.out.println("CompletableFuture get: " +
                                 cf.get(5, TimeUnit.SECONDS));
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    System.out.println("Exit the client...");
}
 
Example #4
Source File: Library.java    From 30-seconds-of-java with MIT License 6 votes vote down vote up
/**
 * Performs HTTP POST request.
 * Credits https://stackoverflow.com/questions/3324717/sending-http-post-request-in-java
 * @param address the URL of the connection in String format, like "http://www.google.com"
 * @param arguments the body of the POST request, as a HashMap
 * @return response object
 * @throws IOException if an I/O error occurs
 * @throws InterruptedException if the operation is interrupted
 */
public static HttpResponse<String> httpPost(String address, HashMap<String, String> arguments)
    throws IOException, InterruptedException {
  var sj = new StringJoiner("&");
  for (var entry : arguments.entrySet()) {
    sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "="
        + URLEncoder.encode(entry.getValue(), "UTF-8"));
  }
  var out = sj.toString().getBytes(StandardCharsets.UTF_8);
  var request = HttpRequest.newBuilder()
      .uri(URI.create(address))
      .headers("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
      .POST(BodyPublishers.ofByteArray(out))
      .build();

  return HttpClient.newHttpClient().send(request, BodyHandlers.ofString());
}
 
Example #5
Source File: AbstractRequester.java    From catnip with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected void handleRouteJsonBodySend(@Nonnull final Route finalRoute, @Nonnull final QueuedRequest request) {
    final OutboundRequest r = request.request();
    final String encoded;
    if(r.object() != null) {
        for(final Extension extension : catnip.extensionManager().extensions()) {
            for(final CatnipHook hook : extension.hooks()) {
                r.object(hook.rawRestSendObjectHook(finalRoute, r.object()));
            }
        }
        encoded = JsonWriter.string(r.object());
    } else if(r.array() != null) {
        encoded = JsonWriter.string(r.array());
    } else {
        encoded = null;
    }
    executeHttpRequest(finalRoute, encoded == null ? BodyPublishers.noBody() : BodyPublishers.ofString(encoded), request, "application/json");
}
 
Example #6
Source File: ExternalMessageSignerService.java    From teku with Apache License 2.0 6 votes vote down vote up
private SafeFuture<BLSSignature> sign(final Bytes signingRoot) {
  final String publicKey = blsPublicKey.getPublicKey().toString();
  return SafeFuture.ofComposed(
      () -> {
        final String requestBody = createSigningRequestBody(signingRoot);
        final URI uri = signingServiceUrl.toURI().resolve("/signer/sign/" + publicKey);
        final HttpRequest request =
            HttpRequest.newBuilder()
                .uri(uri)
                .timeout(timeout)
                .POST(BodyPublishers.ofString(requestBody))
                .build();
        return HttpClient.newHttpClient()
            .sendAsync(request, BodyHandlers.ofString())
            .handleAsync(this::getBlsSignature);
      });
}
 
Example #7
Source File: ImagesJDBCTemplateDao.java    From crate-sample-apps with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, String> insertImage(final String digest, byte[] decoded) {
    var blobUri = this.createBlobUri(digest);
    var request = HttpRequest.newBuilder(blobUri).
            PUT(BodyPublishers.ofByteArray(decoded)).build();
    try {
        var response = client.send(request, HttpResponse.BodyHandlers.ofString());
        var result = new HashMap<String, String>();
        result.put("digest", digest);
        result.put("url", "/image/" + digest);
        result.put("status", String.valueOf(response.statusCode()));
        return result;
    } catch (IOException | InterruptedException e) {
        throw new DataIntegrityViolationException("Failed to call blob endpoint", e);
    }
}
 
Example #8
Source File: UserRestClient.java    From Mastering-Microservices-with-Java-Third-Edition with MIT License 6 votes vote down vote up
public void putUser() throws Exception {
  UserVO userVO = new UserVO();
  userVO.setId("3");
  userVO.setName("X User 1");
  userVO.setAddress("X Address 1");
  userVO.setCity("X City 1");
  userVO.setPhoneNo("1234567899");
  HttpRequest request = restClient.requestBuilder(
      URI.create(userEndpoint + "/3"),
      Optional.empty()
  ).PUT(BodyPublishers.ofString(objectMapper.writeValueAsString(userVO))).build();
  HttpResponse<String> response = restClient.send(request);
  LOG.info("Response status code: {}", response.statusCode());
  LOG.info("Response headers: {}", response.headers());
  LOG.info("Response body: {}", response.body());
}
 
Example #9
Source File: UserRestClient.java    From Mastering-Microservices-with-Java-Third-Edition with MIT License 6 votes vote down vote up
public void postUser() throws Exception {
  UserVO userVO = new UserVO();
  userVO.setId("3");
  userVO.setName("X User");
  userVO.setAddress("X Address");
  userVO.setCity("X City");
  userVO.setPhoneNo("1234567890");
  HttpRequest request = restClient.requestBuilder(
      URI.create(userEndpoint),
      Optional.empty()
  ).POST(BodyPublishers.ofString(objectMapper.writeValueAsString(userVO))).build();
  HttpResponse<String> response = restClient.send(request);
  LOG.info("Response status code: {}", response.statusCode());
  LOG.info("Response headers: {}", response.headers());
  LOG.info("Response body: {}", response.body());
}
 
Example #10
Source File: UserRestClient.java    From Mastering-Microservices-with-Java-Third-Edition with MIT License 6 votes vote down vote up
public void putUser() throws Exception {
  UserVO userVO = new UserVO();
  userVO.setId("3");
  userVO.setName("X User 1");
  userVO.setAddress("X Address 1");
  userVO.setCity("X City 1");
  userVO.setPhoneNo("1234567899");
  HttpRequest request = restClient.requestBuilder(
      URI.create(userEndpoint + "/3"),
      Optional.empty()
  ).PUT(BodyPublishers.ofString(objectMapper.writeValueAsString(userVO))).build();
  HttpResponse<String> response = restClient.send(request);
  LOG.info("Response status code: {}", response.statusCode());
  LOG.info("Response headers: {}", response.headers());
  LOG.info("Response body: {}", response.body());
}
 
Example #11
Source File: UserRestClient.java    From Mastering-Microservices-with-Java-Third-Edition with MIT License 6 votes vote down vote up
public void postUser() throws Exception {
  UserVO userVO = new UserVO();
  userVO.setId("3");
  userVO.setName("X User");
  userVO.setAddress("X Address");
  userVO.setCity("X City");
  userVO.setPhoneNo("1234567890");
  HttpRequest request = restClient.requestBuilder(
      URI.create(userEndpoint),
      Optional.empty()
  ).POST(BodyPublishers.ofString(objectMapper.writeValueAsString(userVO))).build();
  HttpResponse<String> response = restClient.send(request);
  LOG.info("Response status code: {}", response.statusCode());
  LOG.info("Response headers: {}", response.headers());
  LOG.info("Response body: {}", response.body());
}
 
Example #12
Source File: UserRestClient.java    From Mastering-Microservices-with-Java-Third-Edition with MIT License 6 votes vote down vote up
public void postUser() throws Exception {
  UserVO userVO = new UserVO();
  userVO.setId("3");
  userVO.setName("X User");
  userVO.setAddress("X Address");
  userVO.setCity("X City");
  userVO.setPhoneNo("1234567890");
  HttpRequest request = restClient.requestBuilder(
      URI.create(userEndpoint),
      Optional.empty()
  ).POST(BodyPublishers.ofString(objectMapper.writeValueAsString(userVO))).build();
  HttpResponse<String> response = restClient.send(request);
  LOG.info("Response status code: {}", response.statusCode());
  LOG.info("Response headers: {}", response.headers());
  LOG.info("Response body: {}", response.body());
}
 
Example #13
Source File: UserRestClient.java    From Mastering-Microservices-with-Java-Third-Edition with MIT License 6 votes vote down vote up
public void putUser() throws Exception {
  UserVO userVO = new UserVO();
  userVO.setId("3");
  userVO.setName("X User 1");
  userVO.setAddress("X Address 1");
  userVO.setCity("X City 1");
  userVO.setPhoneNo("1234567899");
  HttpRequest request = restClient.requestBuilder(
      URI.create(userEndpoint + "/3"),
      Optional.empty()
  ).PUT(BodyPublishers.ofString(objectMapper.writeValueAsString(userVO))).build();
  HttpResponse<String> response = restClient.send(request);
  LOG.info("Response status code: {}", response.statusCode());
  LOG.info("Response headers: {}", response.headers());
  LOG.info("Response body: {}", response.body());
}
 
Example #14
Source File: TestResponse.java    From mangooio with Apache License 2.0 5 votes vote down vote up
/**
 * Sets a String body to the request
 *
 * @param body The request body to use
 * 
 * @return TestResponse instance
 */
public TestResponse withStringBody(String body) {
    if (StringUtils.isNotBlank(body)) {
        this.body = BodyPublishers.ofString(body);   
    }
    
    return this;
}
 
Example #15
Source File: HttpClientExample.java    From tutorials with MIT License 5 votes vote down vote up
public static void httpPostRequest() throws URISyntaxException, IOException, InterruptedException {
    HttpClient client = HttpClient.newBuilder()
        .version(HttpClient.Version.HTTP_2)
        .build();
    HttpRequest request = HttpRequest.newBuilder(new URI("http://jsonplaceholder.typicode.com/posts"))
        .version(HttpClient.Version.HTTP_2)
        .POST(BodyPublishers.ofString("Sample Post Request"))
        .build();
    HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
    String responseBody = response.body();
    System.out.println("httpPostRequest : " + responseBody);
}
 
Example #16
Source File: TestResponse.java    From mangooio with Apache License 2.0 5 votes vote down vote up
/**
 * Simulates a FORM post by setting:
 * 
 * Content-Type to application/x-www-form-urlencoded
 * HTTP method to POST
 * URLEncoding of the given parameters
 * 
 * @param parameters The parameters to use
 * @return TestResponse instance
 */
public TestResponse withForm(Multimap<String, String> parameters) {
    String form = parameters.entries()
            .stream()
            .map(entry -> entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), Charset.forName(Default.ENCODING.toString())))
            .collect(Collectors.joining("&"));
    
    this.httpRequest.header(CONTENT_TYPE, "application/x-www-form-urlencoded");
    this.body = BodyPublishers.ofString(form);
    this.method = Methods.POST.toString();
    
    return this;
}
 
Example #17
Source File: ImagesJDBCTemplateDao.java    From crate-sample-apps with Apache License 2.0 5 votes vote down vote up
@Override
public boolean imageExists(@NonNull final String digest) {
    var request = HttpRequest
            .newBuilder(this.createBlobUri(digest))
            .method("HEAD", HttpRequest.BodyPublishers.noBody())
            .build();
    try {
        var response = client.send(request, HttpResponse.BodyHandlers.discarding());
        return response.statusCode() == HttpStatus.OK.value();
    } catch (IOException | InterruptedException e) {
        throw new DataIntegrityViolationException("Failed to call blob endpoint", e);
    }
}
 
Example #18
Source File: ReactivePost.java    From demo-java-x with MIT License 5 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {
	HttpClient client = HttpClient.newBuilder().build();
	HttpRequest post = HttpRequest
			.newBuilder(POSTMAN_POST)
			.POST(new LoggingBodyPublisher(BodyPublishers.ofFile(LARGE_JSON)))
			.header("Content-Type", "application/json")
			.build();
	HttpResponse<String> response = client
			.send(post, BodyHandlers.ofString());

	System.out.println("Status: " + response.statusCode());
	System.out.println(response.body());
}
 
Example #19
Source File: HttpClientDemo.java    From Learn-Java-12-Programming with MIT License 5 votes vote down vote up
private static void post(){
    HttpClient httpClient = HttpClient.newHttpClient();

    HttpRequest req = HttpRequest.newBuilder()
            .uri(URI.create("http://localhost:3333/something"))
            .POST(BodyPublishers.ofString("Hi there!"))
            .build();

    try {
        HttpResponse<String> resp = httpClient.send(req, BodyHandlers.ofString());
        System.out.println("Response: " + resp.statusCode() + " : " + resp.body());
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
 
Example #20
Source File: JavaRequestProcessor.java    From milkman with MIT License 5 votes vote down vote up
@Override
public void setBody(String body) {
	if (method.equals("GET") || method.equals("DELETE")) {
		builder.method(method, BodyPublishers.noBody());
	} else {
		builder.method(method, BodyPublishers.ofString(body));
	}
}
 
Example #21
Source File: UserRestClient.java    From Mastering-Microservices-with-Java-Third-Edition with MIT License 5 votes vote down vote up
public void patchUser() throws Exception {
  HttpRequest request = restClient.requestBuilder(
      URI.create(userEndpoint + "/3/name?value=Duke+Williams"), Optional.empty())
      .method("PATCH", BodyPublishers.noBody())
      .build();
  HttpResponse<String> response = restClient.send(request);
  LOG.info("Response status code: {}", response.statusCode());
  LOG.info("Response headers: {}", response.headers());
  LOG.info("Response body: {}", response.body());
}
 
Example #22
Source File: UserRestClient.java    From Mastering-Microservices-with-Java-Third-Edition with MIT License 5 votes vote down vote up
public void patchUser() throws Exception {
  HttpRequest request = restClient.requestBuilder(
      URI.create(userEndpoint + "/3/name?value=Duke+Williams"), Optional.empty())
      .method("PATCH", BodyPublishers.noBody())
      .build();
  HttpResponse<String> response = restClient.send(request);
  LOG.info("Response status code: {}", response.statusCode());
  LOG.info("Response headers: {}", response.headers());
  LOG.info("Response body: {}", response.body());
}
 
Example #23
Source File: UserRestClient.java    From Mastering-Microservices-with-Java-Third-Edition with MIT License 5 votes vote down vote up
public void patchUser() throws Exception {
  HttpRequest request = restClient.requestBuilder(
      URI.create(userEndpoint + "/3/name?value=Duke+Williams"), Optional.empty())
      .method("PATCH", BodyPublishers.noBody())
      .build();
  HttpResponse<String> response = restClient.send(request);
  LOG.info("Response status code: {}", response.statusCode());
  LOG.info("Response headers: {}", response.headers());
  LOG.info("Response body: {}", response.body());
}
 
Example #24
Source File: R2ServerClient.java    From r2cloud with Apache License 2.0 4 votes vote down vote up
private HttpRequest.Builder createJsonRequest(String path, JsonValue json) {
	return createRequest(path).header("Content-Type", "application/json").POST(BodyPublishers.ofString(json.toString(), StandardCharsets.UTF_8));
}
 
Example #25
Source File: RestClient.java    From r2cloud with Apache License 2.0 4 votes vote down vote up
private HttpRequest.Builder createJsonPost(String path, JsonObject obj) {
	return createAuthRequest(path).header("Content-Type", "application/json").POST(BodyPublishers.ofString(obj.toString(), StandardCharsets.UTF_8));
}
 
Example #26
Source File: JavaNetHttpRequester.java    From algoliasearch-client-java-2 with MIT License -1 votes vote down vote up
/**
 * Build the body for the request builder. Handling compression type of the request.
 *
 * @param builder Request Builder
 * @param algoliaRequest HttpClient agnostic Algolia's request
 */
private BodyPublisher buildRequestBody(
    @Nonnull Builder builder, @Nonnull HttpRequest algoliaRequest) {

  if (algoliaRequest.getBody() == null) {
    return java.net.http.HttpRequest.BodyPublishers.noBody();
  }

  if (algoliaRequest.canCompress()) {
    builder.header(Defaults.CONTENT_ENCODING_HEADER, Defaults.CONTENT_ENCODING_GZIP);
  } else {
    builder.header(Defaults.CONTENT_TYPE_HEADER, Defaults.APPLICATION_JSON);
  }

  return BodyPublishers.ofInputStream(algoliaRequest::getBody);
}
 
Example #27
Source File: MultipartBodyPublisher.java    From catnip with BSD 3-Clause "New" or "Revised" License -2 votes vote down vote up
public BodyPublisher build() {
    if(partsSpecificationList.isEmpty()) {
        throw new IllegalStateException("Must have at least one part to build multipart message.");
    }
    addFinalBoundary();
    return BodyPublishers.ofByteArrays(PartsIterator::new);
}
 
Example #28
Source File: AbstractRequester.java    From catnip with BSD 3-Clause "New" or "Revised" License -2 votes vote down vote up
protected void executeHttpRequest(@Nonnull final Route route, @Nullable final BodyPublisher body,
                                  @Nonnull final QueuedRequest request, @Nonnull final String mediaType) {
    final HttpRequest.Builder builder;
    final String apiHostVersion = catnip.options().apiHost() + "/api/v" + catnip.options().apiVersion();
    
    if(route.method() == GET) {
        // No body
        builder = HttpRequest.newBuilder(URI.create(apiHostVersion + route.baseRoute())).GET();
    } else {
        final var fakeBody = request.request.emptyBody();
        builder = HttpRequest.newBuilder(URI.create(apiHostVersion + route.baseRoute()))
                .setHeader("Content-Type", mediaType)
                .method(route.method().name(), fakeBody ? BodyPublishers.ofString(" ") : body);
        if(fakeBody) {
            // If we don't have a body, then the body param is null, which
            // seems to not set a Content-Length. This explicitly tries to set
            // up a request shaped in a way that makes Discord not complain.
            catnip.logAdapter().trace("Set fake body due to lack of body.");
        }
    }
    
    // Required by Discord
    builder.setHeader("User-Agent", "DiscordBot (https://github.com/mewna/catnip, " + CatnipMeta.VERSION + ')');
    // Request more precise ratelimit headers for better timing
    // NOTE: THIS SHOULD NOT BE CONFIGURABLE BY THE END USER
    // This is pretty important for getting timing of things like reaction
    // routes correct, so there's no use for the end-user messing around
    // with this.
    // If they REALLY want it, they can write their own requester.
    builder.setHeader("X-RateLimit-Precision", "millisecond");
    
    if(request.request().needsToken()) {
        builder.setHeader("Authorization", "Bot " + catnip.options().token());
    }
    if(request.request().reason() != null) {
        catnip.logAdapter().trace("Adding reason header due to specific needs.");
        builder.header(Requester.REASON_HEADER, Utils.encodeUTF8(request.request().reason()));
    }
    
    // Update request start time as soon as possible
    // See QueuedRequest docs for why we do this
    request.start = System.nanoTime();
    catnip.options().httpClient().sendAsync(builder.build(), BodyHandlers.ofString())
            .thenAccept(res -> {
                final int code = res.statusCode();
                final String message = "Unavailable to due Java's HTTP client.";
                final long requestEnd = System.nanoTime();
                
                catnip.rxScheduler().scheduleDirect(() ->
                        handleResponse(route, code, message, requestEnd, res.body(), res.headers(), request));
            })
            .exceptionally(e -> {
                request.bucket.failedRequest(request, e);
                return null;
            });
}