【发布时间】:2013-04-06 21:28:24
【问题描述】:
我正在尝试在应用引擎应用程序下使用 urlfetch 发出 POST 请求。
我已按照从 App Engine 文档(此处为 https://developers.google.com/appengine/docs/java/urlfetch/usingjavanet)的“使用 HttpURLConnection”部分下的简单示例中提取的说明(和代码)进行操作。
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 发送的。
这是我对此请求的回复:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>405 Method Not Allowed</title>
<h1>Method Not Allowed</h1><p>The method GET is not allowed for the requested URL.</p>
有人遇到过这个问题吗?
感谢任何帮助。
【问题讨论】:
-
该示例代码对我来说很好,我得到了
// OK部分 -
我也是 - 但是,响应显示 405: Method not allowed。这意味着 HttpURLConnection 发送的是 GET 而不是 POST。我想知道为什么它发送的是 GET 而不是 POST 请求。
-
我仍然不知道为什么 App Engine 文档中的这个示例不起作用。我最终使用此处介绍的方法 (link) 来执行 POST 请求。
标签: java google-app-engine post httpurlconnection urlfetch