2016-02-12 130 views
4

我正在使用在Java中使用wit.ai的虛擬助手,但我堅持提出HTTP請求。我不擅長Java中的HTTP請求,我一直得到錯誤400。wit.ai - 如何在Java中發送請求?

這是我的代碼:

public class CommandHandler { 
public static String getCommand(String command) throws Exception { 

    String url = "https://api.wit.ai/message"; 
    String key = "TOKEN HERE"; 

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

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


    URLConnection connection = new URL(url + "?" + query).openConnection(); 
    connection.setRequestProperty ("Authorization Bearer", key); 
    connection.setRequestProperty("Accept-Charset", charset); 
    InputStream response = connection.getInputStream(); 
    return response.toString(); 
} 

}

這是例子wit.ai給出:

$ curl \ 
    -H 'Authorization: Bearer $TOKEN' \ 
    'https://api.wit.ai/message?v=20141022&q=hello' 

我希望有人能幫助我

+0

我不能說這是原因,但捲曲你'Authoritation:承載[值]'和Java的'授權承載: [值]'(假設'TOKEN'和'key'都已正確設置)。也就是說,你可以打印「url +」?「 +查詢「來查看是否有進一步的差異(儘管我會說沒有)。 – SJuan76

+3

謝謝,我想我忘了承載後的空間,所以它''connection.setRequestProperty(「Authorization」,「Bearer」+ key);' – Julian

+0

嗨@Julian,如果你知道任何基於JAVA的開源項目和正在使用wit.ai api的,請分享一下嗎?謝謝,我正在檢查wit.ai項目,他們有節點sdk,但不是直接java java sdk。謝謝。 –

回答

0

這爲我工作!

connection.setRequestProperty(「Authorization」:「Bearer」+ key);

+0

請用反引號包裝您的代碼,以便將其格式化爲代碼 – YakovL

0

下面是簡單的代碼來快速檢查您的REST API

try { 
     URL url = new URL("https://api.wit.ai/message?v=20170218&q=Hello"); 
     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     conn.setRequestMethod("GET"); 
     conn.setRequestProperty("Accept", "application/json"); 
     conn.setRequestProperty("Authorization", "Bearer addkeyhere"); 

     if (conn.getResponseCode() != 200) { 
      throw new RuntimeException("Failed : HTTP error code : " 
        + conn.getResponseCode()); 
     } 

     BufferedReader br = new BufferedReader(new InputStreamReader(
      (conn.getInputStream()))); 

     String output; 
     System.out.println("Output from Server .... \n"); 
     while ((output = br.readLine()) != null) { 
      System.out.println(output); 
     } 

     conn.disconnect(); 

     } catch (MalformedURLException e) { 

     e.printStackTrace(); 

     } catch (IOException e) { 

     e.printStackTrace(); 

     }