The next follow-up to the last article is the code I used to communicate with the Watson Translation service. But first I want to show the flow of the data:
So basically the SWT client sends a JSON string to the server in the body of the message. You can do this as long as you specify application/json as the Content-Type. For JSON, I use the JSON library for Java over at json.org and its been perfect. I have even begun using this library for all of my in memory objects because then I can easily serialize it out for storage or over the network.
Below you will see the primary code to send this message:
JSONObject payload = new JSONObject(); payload.put("toLang", obj.get("to")); payload.put("text", obj.get("text")); URL url = new URL(pet_bluemix_translation_service); URLConnection connection = url.openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/json"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(payload.toString()); out.close(); //Now get the response BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String n = in.readLine(); StringBuffer sbValue = new StringBuffer(); while(n != null){ sbValue.append(n); n = in.readLine(); } in.close(); final String value = sbValue.toString();
I’m using IBM’s developer SDK for the Watson service. Can be setup within seconds (using Maven or Gradle). Highly recommended.
https://github.com/watson-developer-cloud/java-sdk
That is pretty slick but it can’t be faster than doing it in NodeRed right?