java 如何使用服务使用 www.example.com

nimxete2  于 2023-04-28  发布在  Java
关注(0)|答案(1)|浏览(363)

我想使用www.example进行服务呼叫 www.example.com 方法:下面是我想消费的服务:

@PostMapping(value = "/service", consumes = { "application/x-www-form-urlencoded" })
    public ServiceObligationResponse retrieveServiceObligationResponsesByServiceObligationRequests(
            @Valid @RequestParam Map<String, String> params,
            @RequestHeader(value = KEY, required = true) String key,
            @RequestHeader(value = ID, required = true) String id,
            @RequestHeader(value = AUTH_HEADER, required = true) String authHeader)
            throws CustomUnAuthorizedException {
 Some code ............... 
}

请帮助我是微服务的新手

cu6pst1q

cu6pst1q1#

只需将头和参数添加到RestTemplate对象。

final String uri = "http://localhost:8080/service";

RestTemplate restTemplate = new RestTemplate();

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.set("KEY", "myKey");
headers.set("ID", "myId");
headers.set("AUTH_HEADER", "myAuthHeader");

Map<String, String> params = new HashMap<>();
params.put("param1", "value1");

HttpEntity<Map<String, String>> request = new HttpEntity<>(params , headers);

ResponseEntity<MyResponse> response = restTemplate.exchange(uri, HttpMethod.POST, request, MyResponse.class);

if(response.getStatusCode() == HttpStatus.OK) {
  MyResponse resObj = response.getBody();
  // do something with the response
}

相关问题