Search code examples
javaresthttprequesthttpclienthttpresponse

How to set path and query parameter in HttpRequest?


I am making a REST call to a service that expects a string as a path parameter, how should I pass the string?

My code:

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = new HttpRquest.newBuilder().uri(URI.create(endpoint)).GET.header("Content-Type","application/json").build();
HttpResponse<String> response = client.send(request,Httpresponse.BodyHandlers.ofString());
ObjectMapper objectMapper = new ObjectMapper();
MyClass myClass = new MyClass();
myClass = objectMapper.readValue(response.body.toString(),MyClass.class);

To the endpoint I should add the string myString as a path paramenter. Thanks for the support!


Solution

  • URIBuilder uri = new URIBuilder().setScheme("https").setHost("dog.com");
        List<String> pathSegs = new ArrayList<>();
        pathSegs.add("random");
        pathSegs.add("path");
        pathSegs.add("5");
        uri.setPathSegments(pathSegs);
        System.out.println(uri.build());
    

    Console output: https://dog.com/random/path/5