在控制台[java]中打印Wit.ai响应

时间:2016-07-04 11:50:01

标签: java connection inputstream wit.ai

大家好我试图向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);
    }
}

1 个答案:

答案 0 :(得分: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请求而不是另一个协议。