Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

41.8. RestClient

41.8.1. 创建 RestClient

Bean 注入方式

		
@Value("${REMOTE_BASE_URI:http://localhost:3000}")
String baseURI;

@Bean
RestClient restClient() {
  return RestClient.create(baseURI);
}		
		
		
		
RestClient defaultClient = RestClient.create();

RestClient customClient = RestClient.builder()
  .requestFactory(new HttpComponentsClientHttpRequestFactory())
  .messageConverters(converters -> converters.add(new MyCustomMessageConverter()))
  .baseUrl("https://example.com")
  .defaultUriVariables(Map.of("variable", "foo"))
  .defaultHeader("My-Header", "Foo")
  .requestInterceptor(myCustomInterceptor)
  .requestInitializer(myCustomInitializer)
  .build();		
		
		

41.8.2. Get 操作

		
restClient.get()
	.uri("/employees")
	//...

restClient.get()
	.uri("/employees/{id}", id)
	//...		
		
		

		
List<Employee> employeeList = restClient.get()
    .uri("/employees")
    .accept(MediaType.APPLICATION_JSON)
    .retrieve()
    .body(List.class);
    
ResponseEntity<List> responseEntity = restClient.get()
    .uri("/employees")
    .accept(MediaType.APPLICATION_JSON)
    .retrieve()
    .toEntity(List.class);    		
		
		

41.8.3. Post Json

		
    @Cacheable(value = "translate", key = "#chinese", unless = "#result == null")
    public String translate(String chinese) {
        String english = null;
        RestClient restClient = RestClient.builder().baseUrl(url).build();
        String accessToken = this.getAccessToken();
        HashMap<String, String> data = new LinkedHashMap<String, String>() {{
            put("q", chinese);
            put("from", "zh");
            put("to", "en");
        }};
        ResponseEntity<Translate> response = restClient.post()
                .uri("/rpc/2.0/mt/texttrans/v1-?access_token={access_token}", Map.of("access_token", accessToken))
                .contentType(APPLICATION_JSON)
                .body(data)
                .retrieve()
                .toEntity(Translate.class);

        if (response.getStatusCode() == HttpStatus.OK) {
            Translate translate = response.getBody();
            if (translate.getResult() != null) {
                english = translate.getResult().getTrans_result().get(0).get("dst");
            }
            log.info("Translate english: {}", english);
        } else {
            log.info("Translate: " + response);
        }
        return english;
    }		
		
		

41.8.4. HTTP Authorization Basic

		
	@GetMapping("/{device}/test")
    public String get(@PathVariable String device) throws InterruptedException {

        String username = System.getProperty("username", "admin");
        String password = System.getProperty("password", "uPQKFe98IwZCzgVGjbWIQRyRyyecb2Ha");

        Base64.Encoder encoder = Base64.getEncoder();
        String authorization = encoder.encodeToString((username + ":" + password).getBytes(StandardCharsets.UTF_8));
        RestClient restClient = RestClient.builder()
                .baseUrl("http://gpt.netkiller.cn:8080")
                .defaultHeader("Authorization", "Basic " + authorization)
                .build();

        String question = "test";

        String result = restClient.get().uri(uriBuilder -> uriBuilder
                .path("/ask/cache_chatgpt")
                .queryParam("question", question)
                .build()).retrieve().body(String.class);

        return result;
    }		
		
		

41.8.5. onStatus

		
		ResponseEntity<JsonObject> responseEntity = restClient.get()
                .uri(uriBuilder -> uriBuilder
                        .path("/articles/1.html")
                        .queryParam("question", URLEncoder.encode(question, StandardCharsets.UTF_8))
                        .build())
                .retrieve()
                .onStatus(status -> status.value() == 404, (request, response) -> {
                	throw new ArticleNotFoundException(response)
                }).toEntity(JsonObject.class);
		
		

41.8.6. 下载二进制流

		
@SneakyThrows
    public Optional<String> speechSynthesizer(String session, String text, String filePath) {
        if (text.isEmpty()) {
            throw new AigcException.AigcSpeechSynthesizerException("文本不能为空");
        }
        RestClient client = RestClient.create("http://nls-gateway-cn-shanghai.aliyuncs.com");

        LinkedHashMap<String, Object> data = new LinkedHashMap<>();
        data.put("appkey", this.appKey);
        data.put("token", getToken());
        data.put("text", text);
        data.put("format", "mp3");

        if (isEnglishText(text)) {
            data.put("text", convertString(text));
            data.put("voice", this.english);
            data.put("speech_rate", -250);
        } else {
            data.put("text", text);
            data.put("voice", this.chinese);
            data.put("speech_rate", -80);
        }

        ResponseEntity<byte[]> response = client.post()
                .uri("/stream/v1/tts")
                .contentType(MediaType.APPLICATION_JSON)
                .body(data)
                .retrieve()
                .toEntity(byte[].class);
        if (response.getStatusCode() == HttpStatus.OK) {
            log.debug(response.getHeaders().toString());
            boolean isAudio = response.getHeaders().getContentType().equals(MediaType.valueOf("audio/mpeg"));
            if (isAudio) {

                File file = new File(filePath);
                if (!file.getParentFile().isDirectory()) {
                    boolean directory = file.getParentFile().mkdirs();
                }
                if (file.exists() && file.isFile()) {
                    boolean flag = file.delete();
                }
                if (file.createNewFile()) {
                    try (DataOutputStream dataOutputStream = new DataOutputStream(new FileOutputStream(filePath, true))) {
                        dataOutputStream.write(response.getBody());
                    }
                }
                String audio = filePath.replace("/tmp/audio", audioUrl);
                log.info("speechSynthesizer audio: {}", audio);
                return Optional.ofNullable(audio);
            } else {
                log.info(response.getBody().toString());
            }
        }
        return Optional.empty();
    }