2012-10-31 59 views
1

如何使用Google App Engine的Java運行時的UrlFetch服務執行HTTP PUT請求?Java GAE 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(); 
    } 
} 

我嘗試做相同的POSTPUT,但我一直得到一個 HTTP錯誤不允許的方法。謝謝您的幫助。

參考:https://developers.google.com/appengine/docs/java/urlfetch/overview

不幸的是,GAE Java沒有良好的文檔作爲Python的版本GAE URL的獲取(https://developers.google.com/appengine/docs/python/urlfetch/overview)。任何來自Google的人都想說明原因?

+0

**注:**'typeRef'是TypeReference例如,'mapper'是ObjectMapper實例 – ecbrodie

回答

1

我認爲你的代碼有效。您所看到的HTTP 405來自您要聯繫的服務器(並非所有服務均支持PUT)。您可以嘗試使用curl打網址,如果你想確認這不是你的錯代碼:

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

只是爲了一般的知識...如果我使用'conn.setRequestMethod(「PUT」)我的上面的代碼',我嘗試從一個*不存在的* URL讀取,我從來沒有得到一個404,而是一個405。這正常的行爲? – ecbrodie

+0

我剛剛嘗試'PUT'一個不存在的URL,並得到了404。 –