2

我正在尝试在应用引擎应用程序下使用 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>

有人遇到过这个问题吗?

任何帮助表示赞赏。

4

3 回答 3

1

由于这个问题在 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~ 
<redacted>)", "X-Cloud-Trace-Context": ",<redacted>" }, "json": null, 
"origin": "107.178.194.113", "url": "http://httpbin.org/post"}
于 2017-02-17T22:20:09.480 回答
0

您是否尝试过调用 OutputStreamWriter 的 flush() 方法?

于 2013-08-21T18:30:24.640 回答
0

也许您必须设置内容类型请求属性:

connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
于 2014-09-17T15:05:29.377 回答