0

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!

Prodox21
  • 107
  • 1
  • 2
  • 9
  • [Check this similar question, you'll have to use URIBuilder class from apache client library](https://stackoverflow.com/questions/14043843/how-to-add-parameters-to-all-httpclient-request-methods?noredirect=1&lq=1) – AkSh Aug 31 '21 at 14:21
  • in this way I would get a URL of the type http://www.google.com/search?q=httpclient&btnG=Google+Search&aq=f&oq= as in the example you indicated. I would need to pass the parameters as a path parameter and get an endpoint like: http://www.google.com/search/mystring – Prodox21 Aug 31 '21 at 14:27
  • there is an appendPath(String path) method that you can use. – AkSh Aug 31 '21 at 14:38
  • Sorry but appendPath(String path) it is not present in the list of functions of URIBuilder :/ – Prodox21 Aug 31 '21 at 14:56

2 Answers2

1
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

Dharman
  • 30,962
  • 25
  • 85
  • 135
AkSh
  • 218
  • 1
  • 7
  • The method setPathSegments is undefined for the type org.apache.http.client.utils.URIBuilder, why? – Prodox21 Sep 01 '21 at 12:37
  • That's weird...I've checked the code from my end. [check the doc, it's there too](https://javadoc.io/doc/org.apache.httpcomponents/httpclient/latest/org/apache/http/client/utils/URIBuilder.html) – AkSh Sep 02 '21 at 06:25
  • Now it works, using an outdated version of the maven dependency. Thanks! – Prodox21 Sep 02 '21 at 06:58
0

It's very simple using http-request built on apache HTTP API.

final HttpRequest httpRequest = HttpRequestBuilder.create(
  ClientBuilder.create().build();
)
.build();

MyClass myClass = httpRequest.target(endpoint)
.addParameter(paramKey1, paramValue1)
.addParameter(paramKey2, paramValue2)
.addHeader("Content-Type","application/json")
.get(MyClass.class);
 

Dependency

<dependency>
  <groupId>com.jsunsoft.http</groupId>
  <artifactId>http-request</artifactId>
  <version>2.2.2</version>
</dependency>
Beno
  • 945
  • 11
  • 22