Last active
December 22, 2019 22:10
-
-
Save michael-simons/8165d6b5a5bd39142a1cac9e367cad13 to your computer and use it in GitHub Desktop.
Simple JDK 11+ HTTP Client usage, POST'ing formdata
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.demo; | |
import static java.nio.charset.StandardCharsets.UTF_8; | |
import java.net.URI; | |
import java.net.URLEncoder; | |
import java.net.http.HttpClient; | |
import java.net.http.HttpRequest; | |
import java.net.http.HttpRequest.BodyPublishers; | |
import java.net.http.HttpResponse.BodyHandlers; | |
import java.util.Map; | |
import java.util.stream.Collectors; | |
public class DemoApplication { | |
public static void main(String[] args) throws Exception { | |
var tenant = "4711"; | |
var bodyContent = Map.of("id", 1); | |
var formData = bodyContent.entrySet().stream() | |
.map(e -> URLEncoder.encode(e.getKey(), UTF_8) + "=" + URLEncoder.encode(e.getValue().toString(), UTF_8)) | |
.collect(Collectors.joining("&")); | |
var client = HttpClient.newHttpClient(); | |
var request = HttpRequest.newBuilder() | |
.uri(URI.create("/" + tenant + "/oauth2/v2.0/token")) | |
.POST(BodyPublishers.ofString(formData)) | |
.build(); | |
var response = client.send(request, BodyHandlers.ofString()); | |
System.out.println(response.statusCode()); | |
System.out.println(response.body()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8"?> | |
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | |
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> | |
<modelVersion>4.0.0</modelVersion> | |
<groupId>com.example</groupId> | |
<artifactId>demo</artifactId> | |
<version>0.0.1-SNAPSHOT</version> | |
<properties> | |
<java.version>13</java.version> | |
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> | |
<maven.compiler.source>${java.version}</maven.compiler.source> | |
<maven.compiler.target>${java.version}</maven.compiler.target> | |
<maven.version>3.6.3</maven.version> | |
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version> | |
<maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version> | |
</properties> | |
</project> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment