大家好,我正在尝试向 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);
}
}