0

hi all I'm trying to send a request to Wit to a simple wit application that i've created and I'm doing this in java. I'm trying to print the wit response into the console but the only thing that prints is the following line:

class sun.net.www.protocol.http.HttpURLConnection$HttpInputStream

The code that I am using to send the request is a code that I have found on this forum, I repost it for be more specific:

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

how can i return the wit response?

EDIT: I'm trying with apache as you suggested to me, but it keeps to send me error 400. Here the code:

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);
    }
}
frankjust
  • 19
  • 9

1 Answers1

0

You don't have to use Apache

Taken from the 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();
}

The problem you were having is that the InputStream's toString method is only returning it's class name. Another thing you can try is using HTTPURLConnection rather than just the simple URLConnection, since you know it will be an HTTP request as opposed to another protocol.

Community
  • 1
  • 1
Chris - Jr
  • 398
  • 4
  • 11