Wit.ai - How to send a request in Java?

I am working on a virtual assistant using wit.ai in Java, but I am stuck in an HTTP request. I'm not talking about HTTP requests in Java, and I get a 400 error all the time.

This is my code:

public class CommandHandler {
public static String getCommand(String command) throws Exception {

    String url = "https://api.wit.ai/message";
    String key = "TOKEN HERE";

    String param1 = "20141022";
    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();
}

}

Here is an example wit.ai gives:

$ curl \
  -H 'Authorization: Bearer $TOKEN' \
  'https://api.wit.ai/message?v=20141022&q=hello'

Hope someone can help me.

+4
source share
2 answers

It worked very well for me!

connection.setRequestProperty ("Authorization": "Bearer "+key);
0
source

Below is a simple code to quickly check your holiday api

try {
        URL url = new URL("https://api.wit.ai/message?v=20170218&q=Hello");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Authorization", "Bearer addkeyhere");

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(
            (conn.getInputStream())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

        conn.disconnect();

      } catch (MalformedURLException e) {

        e.printStackTrace();

      } catch (IOException e) {

        e.printStackTrace();

      }
0
source

Source: https://habr.com/ru/post/1628452/


All Articles