1

I'm trying to access one of IBM Watson RESTful interfaces (speech to text) from a Java client using Apache HttpPost, but failing to upload a binary .wav input file properly.

The following 'curl' command works just fine, producing correct results:

curl -u "user:password" -H "content-type: audio/wav" --data-binary @"newfile.wav" "https://stream.watsonplatform.net/speech-to-text/api/v1/recognize" -X POST

The Java client below intends to replicate above curl functionality:

public void speech2text(String user, String password, String file_name) {

  try {

    String ulr_string = "https://stream.watsonplatform.net/speech-to-text/api/v1/recognize";

    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(ulr_string);
    httpPost.addHeader(BasicScheme.authenticate(
     new UsernamePasswordCredentials(user, password), "UTF-8", false));

    httpPost.addHeader("content-type", "audio/wav");
    httpPost.addHeader("content-type", "multipart/form-data");
    // httpPost.addHeader("transfer-encoding", "chunked");

    File input_file = new File(file_name);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addBinaryBody("upfile", input_file, ContentType.DEFAULT_BINARY, "c:\\Temp\\newfile.wav");
    HttpEntity entity = builder.build();
    httpPost.setEntity(entity);

    System.out.println("executing request " + httpPost.getRequestLine());
    Header headers[] = httpPost.getAllHeaders();
    HttpResponse response = httpClient.execute(httpPost);
    HttpEntity resEntity = response.getEntity();

    System.out.println(response.getStatusLine());
    if (resEntity != null) {
      System.out.println(EntityUtils.toString(resEntity));
    }
    if (resEntity != null) {
      EntityUtils.consume(resEntity);
    }

    httpClient.getConnectionManager().shutdown();

} catch (MalformedURLException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
} catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}

}

But the request fails, returning:

HTTP/1.1 400 Bad Request
{
  "code_description": "Bad Request", 
  "code": 400, 
  "error": "unable to transcode data stream audio/wav -> audio/x-float-array "
}

Watson's API requires chunked transfer encoding for large files, but the sample I'm working with is pretty small.

  • I'm having this issue with Ruby as well. The CURL commands works just fine, but when I use the Ruby library, I receive the same error. Did you figure it out? – Alexander Oct 23 '16 at 21:55
  • I figured it out for Ruby. Instead of using `File.read(file_path)`, I used `File.binread(file_path)` to get the binary data. – Alexander Oct 23 '16 at 22:37
  • don't think so it's helpful ..would be great if you provide me any working solution – SeleniumUser Oct 08 '20 at 10:09

0 Answers0