Issue
I'm using the new java.net.http.HttpClient
and would like to change the user agent string. By default it sends Java-http-client/11.0.6
but I'd specify some string on my own.
Any idea how to do this?
Solution
There was an existing bug, it's resolved now.
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse.BodyHandlers;
class Main {
public static void main(String[] args) throws IOException, InterruptedException {
var client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://httpbin.org/headers"))
.setHeader("User-Agent", "Example user agent")
.build();
System.out.println(client.send(request, BodyHandlers.ofString()).body());
}
}
Answered By - Adwait Kumar
Answer Checked By - Marie Seifert (JavaFixing Admin)