【问题标题】:How to work with Patch method in Webclient?如何在 Webclient 中使用 Patch 方法?
【发布时间】:2020-11-25 16:43:16
【问题描述】:

我一直在Webclient 中搜索补丁方法的示例。我的模型类中有四个字段,我需要更新一个字段(即状态字段),因此我决定使用 Patch 方法。但我在网上没有任何例子。

我在RestTemplate 中有一段代码,这里我需要它在Webclient 中,因为我正在迁移到Webclient。下面的代码如何实现?

public void updateProfile(UpdateProfile profile, String uniqueId) {
        
        HttpHeaders headers = new HttpHeaders();
        MediaType mediaType = new MediaType("application", "merge-patch+json");
        headers.setContentType(mediaType);

        HttpEntity<UpdateProfile> entity = new HttpEntity<>(profile, headers);
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        RestTemplate restTemplate = new RestTemplate(requestFactory);

        restTemplate.exchange(firebaseUrl+"/"+path+"/" + uniqueId + ".json", 
                HttpMethod.PATCH, entity, Void.class);
        
    }

【问题讨论】:

    标签: spring-boot webclient resttemplate


    【解决方案1】:

    您可以使用来自网络客户端的以下补丁方法示例,我没有测试过,但我希望您可以使用类似的方法。

            WebClient webClient = WebClient.create(firebaseUrl);
            webClient.patch()
                     .uri("+path+" + uniqueId + ".json")
                     .contentType(MediaType.valueOf("application/json-patch+json"))
                     .bodyValue(data)
                     .exchange();
    

    记得在你的 pom.xml 中添加以下工件,

             <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-webflux</artifactId>
            </dependency>
    

    【讨论】:

    • 这会更新所有 4 个字段。不仅是状态字段。其余字段更新为 null。
    • 使用了PATCH,可能需要调用其他方法。
    猜你喜欢
    • 2015-11-11
    • 1970-01-01
    • 2019-09-10
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-20
    相关资源
    最近更新 更多