1

如何使用 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();
    }
}

POST我尝试执行与for相同的操作PUT,但我不断收到 Method Not Allowed 的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 )。谷歌的任何人都想说为什么?

4

1 回答 1

1

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

curl -X PUT -d "foo=bar" http://your_site.com/path/to/your/resource
于 2012-10-31T20:49:34.817 回答