rohit-biswas
rohit-biswas

Reputation: 845

IBM Watson Q and A API gives 500 response code

I have written a Java Code to test the Watson Question and Answers API. However, I'm getting response code 500, when I run it. I have checked the api url and my login credentials. The problem seems to be somewhere else. Any hints or debugging suggestions would be of great help.

    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());

When i open the same url with the browser I get this: Watson Error!! Error Encountered!! Unable to communicate with Watson. Whats wrong? Could it be something with the configuration? Or is the server down?

Upvotes: 0

Views: 281

Answers (1)

Stephen C
Stephen C

Reputation: 719386

Any hints or debugging suggestions would be of great help.

  1. Attempt the same request using your web browser ... or the curl utility.

  2. Capture and output the contents of the error stream.


I don't think that this is the cause of your problems, but it is wrong anyway:

DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(query);
wr.flush();

You are writing to an API that expects text (JSON). You should therefore use a Writer, not a data (binary) output stream:

Writer wr = new OutputStreamWriter(con.getOutputStream(), "LATIN-1");
wr.write(query);
wr.flush();

Upvotes: 2

Related Questions