用于POST请求的HttpURLConnection App Engine Java示例不起作用
我正在尝试在app引擎应用程序下使用urlfetch执行POST请求。
我已按照“使用HttpURLConnection”部分下的App Engine文档(此处为https://developers.google.com/appengine/docs/java/urlfetch/usingjavanet )中的简单示例提取的说明(和代码)进行了操作。 。
import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.io.OutputStreamWriter; String message = URLEncoder.encode("my message", "UTF-8"); try { URL url = new URL("http://httpbin.org/post"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write("message=" + message); writer.close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { // OK } else { // Server returned HTTP error code. } } catch (MalformedURLException e) { // ... } catch (IOException e) { // ... }
为了测试这个POST请求,我使用以下网站“ http://httpbin.org/post ”。
获取和连接有效 – 但是,连接是作为GET而不是POST发送的。
以下是我对此请求的回复:
405 Method Not Allowed Method Not Allowed
The method GET is not allowed for the requested URL.
有人遇到过这个问题吗?
任何帮助表示赞赏。
由于这个问题在3年后仍然获得了相当多的观点,我将在此确认文档示例中给出的方法适用于对给定URL发出POST请求,并且自该问题首次发布以来保持不变。 工作代码示例如下:
String message = URLEncoder.encode("my message", "UTF-8"); URL url = new URL("http://httpbin.org/post"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write("message=" + message); writer.close(); StringBuffer responseString = new StringBuffer(); String line; BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = reader.readLine()) != null) { responseString.append(line); } reader.close();
收到以下答复:
Code: 200, message: { "args": {}, "data": "", "files": {}, "form": { "message": "my message" }, "headers": { "Accept-Encoding": "gzip,deflate,br", "Content-Length": "18", "Content-Type": "application/x-www-form-urlencoded", "Host": "httpbin.org", "User-Agent": "AppEngine-Google; (+http://code.google.com/appengine; appid: s~ )", "X-Cloud-Trace-Context": ", " }, "json": null, "origin": "107.178.194.113", "url": "http://httpbin.org/post"}
您是否尝试过调用OutputStreamWriter的flush()方法?
也许您必须设置内容类型请求属性:
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
- 会话超时(session.setMaxInactiveInterval)在Google Appengine中不起作用
- 为什么Eclipse认为app引擎sdk jar是app引擎SDK的目录?
- 使用带自动缩放的java的GAE上的Cron作业失败
- 持久保存@Embeddable的@ElementCollection(Google App Engine,datanucleus)
- 配置Restlet以在Google App Engine上返回JSP?
- GAE入门Java Eclipse Indigo – 无法编译为1.6
- 使用HTTP Basic-Auth和Google App Engine URLFetch服务
- Google App Engine投影查询返回0结果
- JExcel中的编码问题