0

大家好,我正在尝试向 Wit 发送一个请求到我创建的一个简单的 wit 应用程序,我正在 java 中执行此操作。我正在尝试将机智响应打印到控制台中,但唯一打印的是以下行:

class sun.net.www.protocol.http.HttpURLConnection$HttpInputStream

我用来发送请求的代码是我在这个论坛上找到的代码,为了更具体,我重新发布它:

public static String getCommand(String command) throws Exception {

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

            String param1 = "my_param";
            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();
    }

我怎样才能回复机智的回应?

编辑:我正在尝试使用您向我建议的 apache,但它一直向我发送错误 400。代码如下:

public static void getCommand2(String command) throws Exception {
    String query = URLEncoder.encode(command, "UTF-8");
    String key = "my_key";

    String url = "https://api.wit.ai/message?v="+my_code+"q"+query;

    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(url);

    // add request header
    request.addHeader("Authorization: Bearer", key);
    HttpResponse response = client.execute(request);

    System.out.println("Response Code : " 
                + response.getStatusLine().getStatusCode());

    BufferedReader rd = new BufferedReader(
        new InputStreamReader(response.getEntity().getContent()));

    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }
}
4

1 回答 1

0

您不必使用 Apache

取自 Wit.ai android-sdk。

public static String convertStreamToString(InputStream is) throws IOException
{
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line;

    while ((line = reader.readLine()) != null)
    {
        sb.append(line);
    }

    is.close();

    return sb.toString();
}

您遇到的问题是 InputStream 的 toString 方法只返回它的类名。您可以尝试的另一件事是使用 HTTPURLConnection 而不仅仅是简单的 URLConnection,因为您知道它将是一个 HTTP 请求,而不是另一个协议。

于 2016-07-06T02:37:26.007 回答