我编写了一个Java代码来测试Watson Question and Answers API。但是,当我运行它时,我收到响应代码500。我检查了api url和我的登录凭据。问题似乎在其他地方。任何提示或调试建议都会有很大的帮助。
String url = "https://watson-wdc01.ihost.com/instance/526/deepqa/v1/question";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
String userCredentials = "username:password";
String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes());
con.setRequestProperty ("Authorization", basicAuth);
con.setRequestProperty("X-SyncTimeout", "30");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Cache-Control", "no-cache");
con.setRequestMethod("POST");
String query = "{\"question\": {\"questionText\": \"" + "What are the common respiratory diseases?" + "\"}}";
System.out.println(query);
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(query);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
当我用浏览器打开相同的网址时,我得到了这个: 沃森错误!! 遇到错误!! 无法与Watson沟通。 怎么了?可能是配置的东西?或者服务器停机了吗?
答案 0 :(得分:2)
任何提示或调试建议都会有很大帮助。
使用您的网络浏览器...或curl
实用程序尝试相同的请求。
捕获并输出错误流的内容。
我不认为这是你问题的原因,但无论如何都是错的:
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(query);
wr.flush();
您正在写一个需要文本(JSON)的API。因此,您应该使用Writer
,而不是数据(二进制)输出流:
Writer wr = new OutputStreamWriter(con.getOutputStream(), "LATIN-1");
wr.write(query);
wr.flush();