【发布时间】:2012-10-31 18:35:02
【问题描述】:
如何使用 UrlFetch 服务为 Google App Engine 的 Java 运行时执行 HTTP PUT 请求?
我的应用程序中的以下代码将发送一个 POST 请求:
URL url = ...;
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(MAX_TIMEOUT); // Maximum allowable timeout on GAE of 60 seconds
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
OutputStreamWriter writer = null;
try {
writer = new OutputStreamWriter(conn.getOutputStream(), Charset.forName("utf-8"));
writer.write(jsonContent);
} finally {
if (writer != null)
writer.close();
}
}
InputStream inStream = null;
E response = null; // Unmarshalled using Jackson
try {
inStream = conn.getInputStream();
if (status != 204) { // NO CONTENT => No need to use Jackson to deserialize!
response = mapper.readValue(inStream, typeRef);
}
} finally {
if (inStream != null) {
inStream.close();
}
}
我尝试对PUT 执行与POST 相同的操作,但我不断收到“不允许方法”的405 HTTP 错误。感谢您的帮助。
参考:https://developers.google.com/appengine/docs/java/urlfetch/overview
不幸的是,GAE Java 的文档不如 Python 版本的 GAE URL fetch(https://developers.google.com/appengine/docs/python/urlfetch/overview)。谷歌的任何人都想知道为什么?
【问题讨论】:
-
注意:
typeRef是 TypeReference 实例,mapper是 ObjectMapper 实例
标签: java google-app-engine http-post urlfetch http-put