Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the user agent string for java.net.http.HttpClient

Tags:

java

http

java-11

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?

like image 421
Ethan Leroy Avatar asked Jan 26 '26 11:01

Ethan Leroy


1 Answers

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());
    }
} 
like image 192
Adwait Kumar Avatar answered Jan 29 '26 03:01

Adwait Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!