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

时间:2013-04-06 21:28:25

标签: java google-app-engine post httpurlconnection urlfetch

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

有人遇到过这个问题吗?

感谢任何帮助。

3 个答案:

答案 0 :(得分:3)

由于这个问题在3年后仍然得到了相当多的观点,我将在此确认method given in the documentation sample适用于对给定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"}

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

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