java - wit.ai - 如何用 Java 发送请求?

标签 java json http https wit.ai

我正在使用 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'

希望有人能帮帮我

最佳答案

下面是快速检查你的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();

      }

关于java - wit.ai - 如何用 Java 发送请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35358232/

相关文章:

arrays - 如何计算 Delphi 中 JSON 数组中元素的数量

delphi - 如何使用 ararat.cz Synapse 库启用 cookie?

javascript - 打印 JSON 属性

java 拖动时滚动

java - Pattern.COMMENTS 总是导致 Matcher.find 失败

java - 错误 : no suitable constructor after update Android Studio from 0. 6.1 到 0.8.9

c# - Cosmos DB - CreateDocumentQuery 不反序列化抽象类型

rest - Nginx 路由到多个 RESTful 端点

android - Retrofit execute方法是后台任务

Java:While循环和数组递增