首页 > 解决方案 > 对 Spring 端点的 Java 请求

问题描述

我正在尝试从 Java 应用程序向另一个用 Spring 编写的应用程序发出请求。现在我得到一个400.

这是我试图达到的 Spring 端点:

@GetMapping(value="/tts/{sessionid}/{fileId}/{text}")
ResponseEntity<byte[]> getAudioFile(
        @ApiParam(value = "Wave SessionId", required = true) @PathVariable String sessionid,
        @ApiParam(value = "File id", required = true) @PathVariable Integer fileId,
        @RequestParam(value = "Text", required = true) String text
) throws Exception

这是我提出有效请求的尝试:

    private void getTtsWave(String waveId, String token, int file_id, String tts_text) {        
        try {
            URL url = new URL(this.recorderendpoint + "/api/tts/" + waveId + "/" + String.valueOf(file_id) + "/{text}?Text=" + tts_text);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty("Authorization", "Bearer " + token);
            int status = con.getResponseCode();
System.out.println(status);
            if (status == 200) {
                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuffer content = new StringBuffer();
                while ((inputLine = in.readLine()) != null) {
                    content.append(inputLine);
                }
                
                if (content != null && !content.equals("")) {
                    System.out.println(content);
                }
                
                in.close();
            }
        } catch (Exception e) {
            log("getTtsWave error: " + e, e.toString()); 
        }
    }

标签: javaspringhttprequest

解决方案


@GetMapping(value="/tts/{sessionid}/{fileId}/{text}")
ResponseEntity<byte[]> getAudioFile

期望这{text}是一个@PathVariable,但在您的getTtsWave方法中,您将其视为 url 的“静态”部分:

this.recorderendpoint + "/api/tts/" + waveId + "/" + String.valueOf(file_id) + "/{text}?Text=" + tts_text

此外,您getAudioFile还有一个参数:

@RequestParam(value = "Text", required = true) String text

这一个参数是必需的请求参数(不是路径参数)

所以我相信你应该改为:

@GetMapping(value="/tts/{sessionid}/{fileId}")
ResponseEntity<byte[]> getAudioFile(
        @ApiParam(value = "Wave SessionId", required = true) @PathVariable String sessionid,
        @ApiParam(value = "File id", required = true) @PathVariable Integer fileId,
        @RequestParam(value = "Text", required = true) String text
) throws Exception

并将您的 URL 构造为:

this.recorderendpoint + "/api/tts/" + waveId + "/" + String.valueOf(file_id) + "?Text=" + tts_text

推荐阅读