wit.ai - 如何在Java中发送请求?

4
我是一个使用Java和wit.ai构建虚拟助手的开发者,但我在进行HTTP请求时遇到了困难。由于我不太擅长Java中的HTTP请求,所以一直收到400错误。
以下是我的代码:
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'

我希望有人能够帮助我


我不能确定这是原因,但在curl中你有Authoritation: Bearer [value],而在Java中则是Authorization Bearer: [value](假设TOKENkey都已正确设置)。话虽如此,你可以打印url + "?" + query来查看是否有进一步的差异(尽管我认为没有)。 - SJuan76
3
谢谢,我想我忘记在Bearer后面加空格了,应该是connection.setRequestProperty("Authorization", "Bearer " + key); - Julian
嗨@Julian,如果您知道任何基于JAVA并使用wit.ai API的开源项目,请分享一下吗?谢谢,我正在查看wit.ai项目,他们有Node SDK,但没有直接的Java SDK。谢谢。 - a3.14_Infinity
2个回答

1
以下是简单的代码,可快速检查您的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();

      }

0

这对我非常有效!

connection.setRequestProperty ("Authorization": "Bearer "+key);

请使用反引号(backticks)将您的代码包装起来,以便以代码格式显示 - YakovL

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接