我正在对期望字符串作为路径参数的服务进行REST调用,我应该如何传递字符串?
我代码:
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);
对于端点,我应该添加字符串myString作为路径参数。感谢大家的支持!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());
控制台输出:https://dog.com/random/path/5
使用基于apache HTTP API的HTTP -request非常简单。
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>
<groupId>com.jsunsoft.http</groupId>
<artifactId>http-request</artifactId>
<version>2.2.2</version>
</dependency>