java webclient post,在Spring Boot中使用WebClient的基本用法总结 | zifangsky的个人博客

package cn.zifangsky.test;

import cn.zifangsky.model.DemoObj;

import org.apache.http.HttpHeaders;

import org.junit.Test;

import org.springframework.http.HttpStatus;

import org.springframework.http.MediaType;

import org.springframework.util.LinkedMultiValueMap;

import org.springframework.util.MultiValueMap;

import org.springframework.web.reactive.function.BodyInserters;

import org.springframework.web.reactive.function.client.WebClient;

import reactor.core.publisher.Mono;

import java.time.Duration;

import java.time.temporal.ChronoUnit;

import java.util.Optional;

/**

* 测试WebClient的基本用法

* @author zifangsky

* @date 2018/9/11

* @since 1.0.0

*/

public class TestWebClient {

private WebClient webClient = WebClient.builder()

.baseUrl("http://127.0.0.1:9090")

.defaultHeader(HttpHeaders.USER_AGENT,"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)")

.defaultCookie("ACCESS_TOKEN", "test_token").build();

/**

* 测试GET请求

*/

@Test

public void testGetMethod(){

Mono response = webClient.get().uri("/rest/testGetHeader?id={id}&name={name}",1,"admin")

.retrieve()

.onStatus(HttpStatus::isError, res -> Mono.error(new RuntimeException(res.statusCode().value() + ":" + res.statusCode().getReasonPhrase())))

.bodyToMono(DemoObj.class).timeout(Duration.of(10, ChronoUnit.SECONDS))

// .doAfterSuccessOrError((obj, ex) -> {

// System.out.println(obj);

//

// if(ex != null){

// ex.printStackTrace();

// }

// })

.doOnError(e -> {

System.out.println(e.getMessage());

});

Optional demoObjOptional = response.blockOptional();

demoObjOptional.ifPresent(System.out::println);

}

/**

* 测试POST表单请求

*/

@Test

public void testPostValue(){

MultiValueMap formData = new LinkedMultiValueMap<>(2);

formData.add("id", "1");

formData.add("name", "admin");

Mono response = webClient.post().uri("/rest/testPostValue")

.contentType(MediaType.APPLICATION_FORM_URLENCODED)

.body(BodyInserters.fromFormData(formData))

.retrieve()

.bodyToMono(DemoObj.class).timeout(Duration.of(10, ChronoUnit.SECONDS));

DemoObj demoObj = response.block();

System.out.println(demoObj);

}

/**

* 测试POST传JSON请求(使用json字符串)

*/

@Test

public void testPostJson(){

Mono response = webClient.post().uri("/rest/testPostJson")

.contentType(MediaType.APPLICATION_JSON_UTF8)

.body(BodyInserters.fromObject("{\"id\":1,\"name\":\"admin\"}"))

.retrieve()

.bodyToMono(DemoObj.class).timeout(Duration.of(10, ChronoUnit.SECONDS));

DemoObj demoObj = response.block();

System.out.println(demoObj);

}

/**

* 测试POST传JSON请求(使用Java Bean)

*/

@Test

public void testPostJson2(){

DemoObj requestData = new DemoObj();

requestData.setId(1L);

requestData.setName("admin");

Mono response = webClient.post().uri("/rest/testPostJson")

.contentType(MediaType.APPLICATION_JSON_UTF8)

// .body(Mono.just(requestData), DemoObj.class)

.syncBody(requestData)

.retrieve()

.bodyToMono(DemoObj.class).timeout(Duration.of(10, ChronoUnit.SECONDS));

DemoObj demoObj = response.block();

System.out.println(demoObj);

}

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在Spring Boot,RestTemplate是一个用于访问RESTful API的HTTP客户端工具。您可以使用RestTemplate来执行HTTP请求并获取响应。以下是使用RestTemplate的基本步骤: 1. 在Spring Boot应用程序添加RestTemplate依赖项。如果您使用的是Maven,则可以在pom.xml文件添加以下依赖项: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 2. 在Java创建一个RestTemplate对象。您可以使用Spring Boot的自动配置机制来创建RestTemplate对象。在您的类使用@Autowired注解即可创建RestTemplate对象。 ``` @Autowired private RestTemplate restTemplate; ``` 3. 使用RestTemplate执行HTTP请求。您可以使用RestTemplate的不同方法执行GET、POST、PUT、DELETE等HTTP请求。例如,以下是使用RestTemplate执行GET请求的示例代码: ``` String url = "http://example.com/api/v1/users"; User[] users = restTemplate.getForObject(url, User[].class); ``` 在这个例子,我们使用getForObject方法执行一个GET请求,将返回的JSON数据映射为一个User数组。 4. 处理响应。您可以使用RestTemplate的不同方法来处理响应。例如,以下是处理响应的示例代码: ``` ResponseEntity<String> response = restTemplate.getForEntity(url, String.class); HttpStatus statusCode = response.getStatusCode(); String responseBody = response.getBody(); ``` 在这个例子,我们使用getForEntity方法执行一个GET请求,并获取响应实体。我们使用getStatusCode方法获取HTTP状态码,使用getBody方法获取响应体。 这是使用RestTemplate的基本步骤。您可以使用RestTemplate执行不同类型的HTTP请求,并处理响应。 ### 回答2: Spring Boot的RestTemplate是一个用于发送HTTP请求并接收HTTP响应的模板类。使用RestTemplate可以简化开发人员对HTTP请求的处理,可以发送GET、POST、PUT、DELETE等不同类型的请求,并且可以处理返回的JSON或XML格式的数据。 使用RestTemplate首先需要在Spring Boot项目添加相应的依赖,一般在pom.xml文件添加如下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 接下来,可以在代码使用RestTemplate类的实例来发送HTTP请求。首先需要在Spring Boot配置类配置RestTemplate的Bean: ```java @Bean public RestTemplate restTemplate() { return new RestTemplate(); } ``` 然后,可以在其他类使用@Autowired注解将RestTemplate注入进行使用: ```java @Autowired private RestTemplate restTemplate; ``` 接下来,可以使用RestTemplate实例的各种方法来发送HTTP请求,例如发送GET请求: ```java String url = "http://api.example.com/getData"; ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class); String responseBody = responseEntity.getBody(); ``` 还可以发送POST请求,并传递参数和请求体: ```java String url = "http://api.example.com/submitData"; MultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>(); requestParams.add("param1", "value1"); requestParams.add("param2", "value2"); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(requestParams, headers); ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class); String responseBody = responseEntity.getBody(); ``` 以上是RestTemplate的基本使用方法,开发人员可以根据实际需求来调用不同的方法来发送HTTP请求和处理响应结果。 ### 回答3: 在Spring Boot,可以使用RestTemplate来进行HTTP请求和响应的处理。RestTemplate是一个提供了简化HTTP请求的高级工具类。 首先,需要在Spring Boot的项目引入RestTemplate的依赖。可以在pom.xml文件添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 在完成依赖引入后,可以在代码实例化一个RestTemplate对象,并使用其提供的方法发送HTTP请求。以下是一个示例: ```java // 实例化RestTemplate对象 RestTemplate restTemplate = new RestTemplate(); // 发送GET请求,并返回响应结果 String url = "https://api.example.com/data"; String response = restTemplate.getForObject(url, String.class); // 发送POST请求,并传递JSON数据 String url = "https://api.example.com/data"; String requestBody = "{\"name\":\"John\",\"age\":30}"; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers); ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class); String response = responseEntity.getBody(); ``` 以上示例使用了RestTemplate提供的getForObject方法发送了一个GET请求,并返回了响应结果;同时也使用postForEntity方法发送了一个POST请求,并传递了JSON数据。 除了GET和POST请求之外,RestTemplate还提供了其他常用的HTTP方法,例如PUT、DELETE等,可以根据业务需求选择适合的方法进行使用。 需要注意的是,RestTemplate是在Spring 5.x被标记为过时API,建议在新项目使用WebClient代替。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值