Well, with GAE it is easy to develop applications on the cloud. But various limitations sometimes make people feel really uncomfortable when their usual behavior being considered as illegal according to the Google Laws.
You are not allowed to use any library related to .net package which may possibly generate more threads. But in order to make any invocation of other RESTful web services, we need to do something to both satisfy the requirement of Google and us.
In the official document, GAE recommends to use the HttpURLConnection class, which is a little bit too simpler to use, which means it brings various problems when dealing with complicated data types.
Here I will invoke a remote RESTful web service which will accept the format of JSON. Here is the code:
try {
URL url = new URL("http://localhost:8183/users/" +user+"/content");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
String json = content.toJSON().toString();
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(json);
writer.close();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
System.out.println("sssssss");
} else {
System.out.println(connection.getResponseMessage());
System.out.println("ffffffff");
}
} catch (Exception e) {
e.printStackTrace();
}
Looks easy, ha, yep, quite straightforward. Remember to add those content-type in the connection for the receiver to recognize the format you are sending. While you are only allowed to send String or Char[], so hurry up and write your own parsing functions.
No comments:
Post a Comment