如何使用 Google App Engine 的 Java 运行时的 UrlFetch 服务发出 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 ) 那样好的文档。 Google 的任何人都想说为什么吗?
最佳答案
我认为你的代码有效。您看到的 HTTP 405
来自您正在联系的服务器(并非所有服务都支持 PUT
)。如果您想确认不是您的代码有问题,可以尝试使用 curl
来访问该 URL:
curl -X PUT -d "foo=bar" http://your_site.com/path/to/your/resource
关于java - Java GAE UrlFetch 是否支持 HTTP PUT?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13165438/