【问题标题】:Does Java GAE UrlFetch support HTTP PUT?Java GAE UrlFetch 是否支持 HTTP PUT?
【发布时间】: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


【解决方案1】:

我认为您的代码有效。您看到的HTTP 405 来自您正在联系的服务器(并非所有服务都支持PUT)。如果您想确认不是您的代码有问题,可以尝试使用curl 来点击该 URL:

curl -X PUT -d "foo=bar" http://your_site.com/path/to/your/resource

【讨论】:

  • 仅用于一般知识...如果我将上面的代码与conn.setRequestMethod("PUT") 一起使用并尝试从 不存在 URL 读取,我永远不会得到 404 但而是 405。这是正常行为吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-07
  • 1970-01-01
  • 1970-01-01
  • 2012-05-11
  • 2014-08-21
  • 2013-01-24
相关资源
最近更新 更多