0

我编写了一个 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());

当我用浏览器打开相同的 url 时,我得到这个:Watson 错误!!遇到错误!!无法与 Watson 通信。怎么了?可能与配置有关吗?还是服务器宕机了?

4

1 回答 1

2

任何提示或调试建议都会有很大帮助。

  1. curl使用您的网络浏览器...或实用程序尝试相同的请求。

  2. 捕获并输出错误流的内容。


我不认为这是你的问题的原因,但无论如何它是错误的:

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();
于 2015-04-12T01:49:34.637 回答