Java
This Java example requires a json package to get support for JSON, e.g. you can download a proper json package from JSON.simple - A simple Java toolkit for JSON
The thesaurus web service can accessed in Java using the HttpURLConnection class. You can start using the following code, make sure to use your own application key!
import java.io.BufferedReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import org.json.simple.*; // json package, download at http://code.google.com/p/json-simple/
public class Thesaurus {
public static void main(String[] args) {
// NOTE: replace test_only with your own key
new SendRequest("peace", "en_US", "test_only", "json");
}
} // end of Thesaurus
class SendRequest {
final String endpoint = "http://thesaurus.altervista.org/thesaurus/v1";
public SendRequest(String word, String language, String key, String output) {
try {
URL serverAddress = new URL(endpoint + "?word="+URLEncoder.encode(word, "UTF-8")+"&language="+language+"&key="+key+"&output="+output);
HttpURLConnection connection = (HttpURLConnection)serverAddress.openConnection();
connection.connect();
int rc = connection.getResponseCode();
if (rc == 200) {
String line = null;
BufferedReader br = new BufferedReader(new java.io.InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null)
sb.append(line + '\n');
JSONObject obj = (JSONObject) JSONValue.parse(sb.toString());
JSONArray array = (JSONArray)obj.get("response");
for (int i=0; i < array.size(); i++) {
JSONObject list = (JSONObject) ((JSONObject)array.get(i)).get("list");
System.out.println(list.get("category")+":"+list.get("synonyms"));
}
} else System.out.println("HTTP error:"+rc);
connection.disconnect();
} catch (java.net.MalformedURLException e) {
e.printStackTrace();
} catch (java.net.ProtocolException e) {
e.printStackTrace();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
} // end of SendRequest
Put the java code above in a file named Thesaurus.java and compile it:
javac -cp json_simple-1.1.jar Thesaurus.java
Now you are ready to run your compiled code:
java -cp .;json_simple-1.1.jar Thesaurus
Make sure to run the Java example with JDK 1.5 or later.
|