Java 11: New HTTP client send POST requests with x-www-form-urlencoded parameters

I think the following is the best way to achieve this using Java 11: Map<String, String> parameters = new HashMap<>(); parameters.put(“a”, “get_account”); parameters.put(“account”, account); String form = parameters.entrySet() .stream() .map(e -> e.getKey() + “=” + URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8)) .collect(Collectors.joining(“&”)); HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url)) .headers(“Content-Type”, “application/x-www-form-urlencoded”) .POST(HttpRequest.BodyPublishers.ofString(form)) .build(); HttpResponse<?> response = client.send(request, … Read more

How to log request/response using java.net.http.HttpClient?

You can log request and responses by specifying-Djdk.httpclient.HttpClient.log=requests on the Java command line. As for testing/mocking you might want to have a look at the offline test: http://hg.openjdk.java.net/jdk/jdk/file/tip/test/jdk/java/net/httpclient/offline/ Depending on what you are looking to achieve you could use a “DelegatingHttpClient” to intercept and log requests and responses too. Besides the Java API documentation there’s … Read more

Allow insecure HTTPS connection for Java JDK 11 HttpClient

As suggested already you need an SSLContext which ignores the bad certificates. The exact code which obtains the SSLContext in one of the links in the question should work by basically creating a null TrustManager which doesn’t look at the certs: private static TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { … Read more

How to upload a file using Java HttpClient library working with PHP

Ok, the Java code I used was wrong, here comes the right Java class: import java.io.File; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.ContentBody; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.util.EntityUtils; public class PostFile { public static void main(String[] args) throws Exception { HttpClient httpclient = new DefaultHttpClient(); … Read more