Java調用Http接口(7,end)--WebClient調用Http接口

WebClient是Spring提供的非阻塞、響應式的Http客戶端,提供同步及異步的API,將會代替RestTemplate及AsyncRestTemplate。文中所使用到的軟件版本:Java 1.8.0_19一、SpringBoot 2.2.1.RELEASE。html

一、服務端

參見Java調用Http接口(1)--編寫服務端 java

二、調用

使用WebClient須要用到Reactor Netty,依賴以下:react

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webflux</artifactId>
        </dependency>
        <dependency>
            <groupId>io.projectreactor.netty</groupId>
            <artifactId>reactor-netty</artifactId>
        </dependency>

2.一、GET請求

    public static void get() {
        String requestPath = "http://localhost:8080/demo/httptest/getUser?userId=1000&userName=李白";
        WebClient webClient = WebClient.create();
        Mono<String> mono = webClient.get().uri(requestPath).retrieve().bodyToMono(String.class);
        //同步方式
        System.out.println("get block返回結果:" + mono.block());
        
        //異步方式
        final CountDownLatch latch = new CountDownLatch(5);
        for (int i = 0; i < 5; i++) {
            requestPath = "http://localhost:8080/demo/httptest/getUser?userId=1000&userName=李白" + i;
            mono = webClient.get().uri(requestPath).retrieve().bodyToMono(String.class);
            mono.subscribe(new Consumer<String>() {
                @Override
                public void accept(String s) {
                    latch.countDown();
                    System.out.println("get subscribe返回結果:" + s);
                }
            });
        }
        
        try {
            latch.await();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

2.二、POST請求(發送鍵值對數據)

    public static void post() {
        String requestPath = "http://localhost:8080/demo/httptest/getUser";
        WebClient webClient = WebClient.create();
        MultiValueMap<String, String> map = new LinkedMultiValueMap <String, String>();
        map.add("userId", "1000");
        map.add("userName", "李白");
        Mono<String> mono = webClient.post().uri(requestPath).bodyValue(map).retrieve().bodyToMono(String.class);
        System.out.println("post返回結果:" + mono.block());
    }

2.三、POST請求(發送JSON數據)

    public static void post2() {
        String requestPath = "http://localhost:8080/demo/httptest/addUser";
        WebClient webClient = WebClient.create();
        String param = "{\"userId\": \"1001\",\"userName\":\"杜甫\"}";
        Mono<String> mono = webClient.post().uri(requestPath).contentType(MediaType.APPLICATION_JSON).bodyValue(param)
                .retrieve().bodyToMono(String.class);
        System.out.println("post json返回結果:" + mono.block());
    }

2.四、上傳文件

    public static void upload() {
        String requestPath = "http://localhost:8080/demo/httptest/upload";
        WebClient webClient = WebClient.create();
        Mono<String> mono = webClient.post().uri(requestPath).contentType(MediaType.APPLICATION_OCTET_STREAM)
                .bodyValue(new FileSystemResource("d:/a.jpg")).retrieve().bodyToMono(String.class);
        System.out.println("upload返回結果:" + mono.block());
    }

2.五、上傳文件及發送鍵值對數據

    public static void mulit() {
        String requestPath = "http://localhost:8080/demo/httptest/multi";
        WebClient webClient = WebClient.create();
        
        MultipartBodyBuilder builder = new MultipartBodyBuilder();
        builder.part("param1", "參數1");
        builder.part("param2", "參數2");
        builder.part("file", new FileSystemResource("d:/a.jpg"));
        MultiValueMap<String, HttpEntity<?>> parts = builder.build();
        Mono<String> mono = webClient.post().uri(requestPath)
                .bodyValue(parts).retrieve().bodyToMono(String.class);
        System.out.println("mulit返回結果:" + mono.block());
    }

2.六、完整例子

package com.inspur.demo.http.client;

import java.util.concurrent.CountDownLatch;
import java.util.function.Consumer;

import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.MediaType;
import org.springframework.http.client.MultipartBodyBuilder;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.client.WebClient;

import reactor.core.publisher.Mono;

/**
 * 
 * 經過WebClient調用Http接口
 *
 */
public class WebClientCase {
    /**
     *  GET請求
     */
    public static void get() {
        String requestPath = "http://localhost:8080/demo/httptest/getUser?userId=1000&userName=李白";
        WebClient webClient = WebClient.create();
        Mono<String> mono = webClient.get().uri(requestPath).retrieve().bodyToMono(String.class);
        //同步方式
        System.out.println("get block返回結果:" + mono.block());
        
        //異步方式
        final CountDownLatch latch = new CountDownLatch(5);
        for (int i = 0; i < 5; i++) {
            requestPath = "http://localhost:8080/demo/httptest/getUser?userId=1000&userName=李白" + i;
            mono = webClient.get().uri(requestPath).retrieve().bodyToMono(String.class);
            mono.subscribe(new Consumer<String>() {
                @Override
                public void accept(String s) {
                    latch.countDown();
                    System.out.println("get subscribe返回結果:" + s);
                }
            });
        }
        
        try {
            latch.await();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     *  POST請求(發送鍵值對數據)
     */
    public static void post() {
        String requestPath = "http://localhost:8080/demo/httptest/getUser";
        WebClient webClient = WebClient.create();
        MultiValueMap<String, String> map = new LinkedMultiValueMap <String, String>();
        map.add("userId", "1000");
        map.add("userName", "李白");
        Mono<String> mono = webClient.post().uri(requestPath).bodyValue(map).retrieve().bodyToMono(String.class);
        System.out.println("post返回結果:" + mono.block());
    }
    
    /**
     *  POST請求(發送json數據)
     */
    public static void post2() {
        String requestPath = "http://localhost:8080/demo/httptest/addUser";
        WebClient webClient = WebClient.create();
        String param = "{\"userId\": \"1001\",\"userName\":\"杜甫\"}";
        Mono<String> mono = webClient.post().uri(requestPath).contentType(MediaType.APPLICATION_JSON).bodyValue(param)
                .retrieve().bodyToMono(String.class);
        System.out.println("post json返回結果:" + mono.block());
    }
    
    /**
     * 上傳文件
     */
    public static void upload() {
        String requestPath = "http://localhost:8080/demo/httptest/upload";
        WebClient webClient = WebClient.create();
        Mono<String> mono = webClient.post().uri(requestPath).contentType(MediaType.APPLICATION_OCTET_STREAM)
                .bodyValue(new FileSystemResource("d:/a.jpg")).retrieve().bodyToMono(String.class);
        System.out.println("upload返回結果:" + mono.block());
    }
    
    /**
     * 上傳文件及發送鍵值對數據
     */
    public static void mulit() {
        String requestPath = "http://localhost:8080/demo/httptest/multi";
        WebClient webClient = WebClient.create();
        
        MultipartBodyBuilder builder = new MultipartBodyBuilder();
        builder.part("param1", "參數1");
        builder.part("param2", "參數2");
        builder.part("file", new FileSystemResource("d:/a.jpg"));
        MultiValueMap<String, HttpEntity<?>> parts = builder.build();
        Mono<String> mono = webClient.post().uri(requestPath)
                .bodyValue(parts).retrieve().bodyToMono(String.class);
        System.out.println("mulit返回結果:" + mono.block());
    }
    
    public static void main(String[] args) {
        get();
        post();
        post2();
        upload();
        mulit();
    }

}
View Code
相關文章
相關標籤/搜索