用于 POST 请求的 HttpURLConnection App Engine Java 示例不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15856215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 21:04:06  来源:igfitidea点击:

HttpURLConnection App Engine Java Example for POST Request does not work

javagoogle-app-engineposthttpurlconnectionurlfetch

提问by Marcio Cabral

I am trying to do a POST request using urlfetch under an app engine application.

我正在尝试在应用引擎应用程序下使用 urlfetch 执行 POST 请求。

I have followed the instructions (and code) extracted from the simple example found at the App Engine documentation (here https://developers.google.com/appengine/docs/java/urlfetch/usingjavanet), under the section "Using HttpURLConnection".

我已按照从 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) {
        // ...
    }

In order to test this POST request, I am using the following website "http://httpbin.org/post".

为了测试这个 POST 请求,我使用了以下网站“ http://httpbin.org/post”。

The fetch and connection works - however, the connection is sent as a GET and not as POST.

获取和连接有效 - 但是,连接是作为 GET 而不是作为 POST 发送的。

Here is the response I get from for this request:

这是我对这个请求的回应:

<!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>

Have anybody run into this issue ?

有没有人遇到过这个问题?

Any help is appreciated.

任何帮助表示赞赏。

回答by Adam

As this question still gets a considerable amount of views 3 years later, I'll confirm here that the method given in the documentation sampleworks fine for making a POST request to the given URL, and has remained unchanged since this question was first posted. The working code sample is as follows:

由于这个问题在 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();

The following response was received:

收到以下回复:

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"}

回答by eimmer

Have you tried calling the flush() method of the OutputStreamWriter?

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

回答by mkxqiu

Maybe you must set content-type request property:

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

connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");