首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >wit.ai -如何在Java中发送请求?

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

Stack Overflow用户
提问于 2016-02-12 16:46:56
回答 2查看 2.1K关注 0票数 4

我正在用Java语言开发一个使用wit.ai的虚拟助手,但我无法发出HTTP请求。我不是Java中HTTP请求的专家,我一直收到一个错误400。

这是我的代码:

代码语言:javascript
运行
复制
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给出的例子:

代码语言:javascript
运行
复制
$ curl \
  -H 'Authorization: Bearer $TOKEN' \
  'https://api.wit.ai/message?v=20141022&q=hello'

我希望有人能帮助我。

EN

回答 2

Stack Overflow用户

发布于 2017-02-18 17:44:17

以下是快速检查rest api的简单代码

代码语言:javascript
运行
复制
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();

      }
票数 1
EN

Stack Overflow用户

发布于 2016-09-03 19:29:48

这对我来说非常有效!

代码语言:javascript
运行
复制
connection.setRequestProperty ("Authorization": "Bearer "+key);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35358232

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档