【问题标题】:Sending binary data with HttpURLConnection使用 HttpURLConnection 发送二进制数据
【发布时间】:2014-09-27 19:27:00
【问题描述】:

我想使用谷歌语音 api,我发现这个 https://github.com/gillesdemey/google-speech-v2/ 解释得很好,但是我试图将它重写成 java。

File filetosend = new File(path);
byte[] bytearray = Files.readAllBytes(filetosend);
URL url = new URL("https://www.google.com/speech-api/v2/recognize?output="+outputtype+"&lang="+lang+"&key="+key);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//method
conn.setRequestMethod("POST");
//header
conn.setRequestProperty("Content-Type", "audio/x-flac; rate=44100");

现在我迷路了...我想我需要将字节数组添加到请求中。在示例中它的行

--data-binary @audio/good-morning-google.flac \

但是 httpurlconnection 类没有附加二进制数据的方法。

【问题讨论】:

    标签: java post google-api httpurlconnection binary-data


    【解决方案1】:

    但它有getOutputStream(),您可以将数据写入其中。您可能还想致电setDoOutput(true)

    【讨论】:

      【解决方案2】:

      下面的代码对我有用。我只是使用commons-io 来简化,但你可以替换它:

          URL url = new URL("https://www.google.com/speech-api/v2/recognize?lang=en-US&output=json&key=" + key);
          HttpURLConnection conn = (HttpURLConnection) url.openConnection();
          conn.setDoOutput(true);
          conn.setRequestMethod("POST");
          conn.setRequestProperty("Content-Type", "audio/x-flac; rate=16000");
          IOUtils.copy(new FileInputStream(flacAudioFile), conn.getOutputStream());
          String res = IOUtils.toString(conn.getInputStream());
      

      【讨论】:

        【解决方案3】:

        对混合的 POST 内容(二进制和字符数据)使用 multipart/form-data 编码

        //set connection property
        connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + <random-value>);
        
        PrintWriter writer = null;
        OutputStream output = connection.getOutputStream();
        writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
        
        
        // Send binary file.
        writer.append("--" + boundary).append("\r\n");
        writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append("\r\n");
        writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName()).append("\r\n");
        writer.append("Content-Transfer-Encoding: binary").append("\r\n");
        writer.append("\r\n").flush();
        

        【讨论】:

        • 第 2 行和第 10 行的边界究竟代表什么?
        • OP 或相应的 API 文档在哪里要求 multipart?
        • @hnnn 边界是当前时间的十六进制(base-16)表示,以毫秒为单位。根据 API,它允许对嵌套的多部分流进行单程处理。访问commons.apache.org/proper/commons-fileupload/apidocs/org/apache/…
        • 我也不确定我是否可以在 google api 中使用 multipart 的东西
        猜你喜欢
        • 1970-01-01
        • 2015-09-18
        • 2017-01-27
        • 2016-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-02
        • 1970-01-01
        相关资源
        最近更新 更多