【问题标题】:Spring Boot - How to send a POST request via a url with query parameters and store the response inside a method?Spring Boot - 如何通过带有查询参数的 url 发送 POST 请求并将响应存储在方法中?
【发布时间】:2021-12-06 04:50:18
【问题描述】:

我有一个 GET 方法生成的 url,它有点像这种格式:

https://service-name/api?param1=<value1>&param2=<value2>&param3=<value3>.....

我需要点击这个网址并将响应(类型为application/x-www-form-urlencoded)存储到一个变量中,以便进一步使用。

问题是它需要在方法内部完成(获取url并传递它以获得响应)。

怎么办?

【问题讨论】:

  • 听起来你需要使用http client,例如restTemplate

标签: java spring-boot rest microservices


【解决方案1】:

对于 Spring Boot 应用程序使用外部 API,您可以使用 RestTemplate。

下面是一个使用示例。您收到的响应是字符串类型。

RestTemplate restTemplate = new RestTemplate();

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.add("Header", "header1");


UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://foo/api/v3/projects/1/labels")
        .queryParam("param1", param1)
        .queryParam("param2", param2);

HttpEntity<?> entity = new HttpEntity<>(headers);

HttpEntity<String> response = restTemplate.exchange(
        builder.toUriString(), 
        HttpMethod.GET, 
        entity, 
        String.class);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-09
    • 1970-01-01
    • 2018-09-11
    • 1970-01-01
    • 2011-06-10
    • 2018-10-15
    • 1970-01-01
    • 2020-05-09
    相关资源
    最近更新 更多