2017-02-04 140 views
0

我發送波形文件使用HTTP API call.In有文檔wit.ai他們表現出的exaple使用curl如何發送POST HTTP請求的Java進行wit.ai音頻

$ curl -XPOST 'https://api.wit.ai/speech?v=20141022' \ 
    -i -L \ 
    -H "Authorization: Bearer $TOKEN" \ 
    -H "Content-Type: audio/wav" \ 
    --data-binary "@sample.wav" 

我使用java和我必須使用java發送此請求,但我無法正確轉換此Java在curl請求。我無法理解什麼是-i,也不知道如何在java的post請求中設置數據二進制。

這我做了什麼至今

public static void main(String args[]) 
{ 
    String url = "https://api.wit.ai/speech"; 
    String key = "token"; 

    String param1 = "20170203"; 
    String param2 = command; 
    String charset = "UTF-8"; 

    String query = String.format("v=%s", 
      URLEncoder.encode(param1, charset)); 


    URLConnection connection = new URL(url + "?" + query).openConnection(); 
    connection.setRequestProperty ("Authorization","Bearer"+ key); 
    connection.setRequestProperty("Content-Type", "audio/wav"); 
    InputStream response = connection.getInputStream(); 
    System.out.println(response.toString()); 
} 
+0

您應該對Java網絡有基本的瞭解,https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html是一個很好的起點。 –

+0

@jerry Chin我確實有,但我很困惑,並得到錯誤,我不親你能轉換嗎?請幫助 –

+0

你可以發佈錯誤和你做了什麼? –

回答

1

這裏是如何的sample.wav寫信給你連接的輸出流,提防有Bearertoken之間的空間其固定在下面的代碼片段:

public static void main(String[] args) throws Exception { 
    String url = "https://api.wit.ai/speech"; 
    String key = "token"; 

    String param1 = "20170203"; 
    String param2 = "command"; 
    String charset = "UTF-8"; 

    String query = String.format("v=%s", 
      URLEncoder.encode(param1, charset)); 


    URLConnection connection = new URL(url + "?" + query).openConnection(); 
    connection.setRequestProperty ("Authorization","Bearer " + key); 
    connection.setRequestProperty("Content-Type", "audio/wav"); 
    connection.setDoOutput(true); 
    OutputStream outputStream = connection.getOutputStream(); 
    FileChannel fileChannel = new FileInputStream(path to sample.wav).getChannel(); 
    ByteBuffer byteBuffer = ByteBuffer.allocate(1024); 

    while((fileChannel.read(byteBuffer)) != -1) { 
     byteBuffer.flip(); 
     byte[] b = new byte[byteBuffer.remaining()]; 
     byteBuffer.get(b); 
     outputStream.write(b); 
     byteBuffer.clear(); 
    } 

    BufferedReader response = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
    String line; 
    while((line = response.readLine()) != null) { 
     System.out.println(line); 
    } 
} 

PS:我已經成功地測試了上面的代碼,它作爲一個魅力。

+0

非常感謝您的幫助。但是,您仍然可以向我解釋卷曲中的-i和-L是什麼? –

+0

-i在輸出中包含標題;如果所請求的頁面已移至新位置,-L將重新執行請求。如果需要更多詳細信息,最好查看https://linux.die.net/man/1/curl。 –