Java通过发送Post请求,获取音频流,并返回给前端

   目前在做一个JavaWeb的开发工作,前端传过来一段文本,JavaWeb作为中间层,将文本转发给下一级服务,接收下一级服务返回的音频流,并返回给前端。
   在网上查看了一些人写的文件流接收方法,结果总是报错,于是自己摸索着写了一下,希望能给小伙伴们一个参考。

/**
     * 文本转语音请求
     *
     * @param url
     * @param paramMap
     * @param textToSpeechResponse
     */
    public static void doPostVoiceData(String url,Map<String, String> paramMap,HttpServletResponse textToSpeechResponse) {
        // 创建Http实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建HttpPost实例
        HttpPost httpPost = new HttpPost(url);
       
        // 请求参数配置
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).setConnectionRequestTimeout(10000).build();
        httpPost.setConfig(requestConfig);
             
        try {       
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
           
            for(Map.Entry<String, String> entry: paramMap.entrySet()) {
                builder.addPart(entry.getKey(),new StringBody(entry.getValue(), ContentType.create("text/plain", Consts.UTF_8)));
            }
                                         
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
           
            HttpResponse response = httpClient.execute(httpPost);// 执行提交
           
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 设置返回请求Header
                String id = response.getHeaders("Id")[0].getValue();   
                String code = response.getHeaders("Code")[0].getValue();
                String message = response.getHeaders("Message")[0].getValue();
               
                textToSpeechResponse.setHeader("Id", id);
                textToSpeechResponse.setHeader("Code", code);
                textToSpeechResponse.setHeader("Message", message); 
               
                OutputStream out = textToSpeechResponse.getOutputStream();
               
                HttpEntity responseEntity = response.getEntity();
                InputStream inputStream = responseEntity.getContent();
                byte[] buf = new byte[1024];
                int count = 0;
                while ((count = inputStream.read(buf)) > 0) {
                    out.write(buf, 0, count);
                }
            } 
        } catch (Exception e) {
            ByteArrayOutputStream baos=new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            logger.error("调用HttpPost失败:"+baos.toString());
        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    logger.error("关闭HttpPost连接失败!");
                }
            }
        }
    }

返回结果如下图:
在这里插入图片描述

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java发送HTTP POST请求非常常见和简单,可以使用HttpURLConnection或HttpClient来实现。获取返回请求头header也很简单,只需要在发送请求后使用getResponseHeader()或getAllHeaders()方法获取即可。 以HttpURLConnection为例,发送POST请求获取返回请求头header的代码如下: ``` URL url = new URL("http://www.example.com/api"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); os.write(jsonString.getBytes()); os.flush(); // 获取返回请求头header Map<String, List<String>> headers = conn.getHeaderFields(); for (Map.Entry<String, List<String>> entry : headers.entrySet()) { String key = entry.getKey(); List<String> values = entry.getValue(); System.out.println(key + ": " + values); } BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); os.close(); conn.disconnect(); ``` 上述代码中,首先创建了一个URL和HttpURLConnection对象,然后设置POST请求的Content-Type,将请求体写入输出中,并发送请求。接着使用conn.getHeaderFields()方法获取返回请求头header并遍历输出。最后读取返回的响应体并关闭连接。 需要注意的是,如果返回的响应头中有多个值,则可以用getList()方法获取并输出。此外,如果需要在请求头中添加自定义的header,则可以使用setRequestProperty()方法来实现。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值