Using Watson Translation service in an Eclipse SWT application Part 2

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

2 thoughts on “Using Watson Translation service in an Eclipse SWT application Part 2

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s