HttpURLConnection App Engine Java Example for POST Request does not work

蓝咒 提交于 2019-12-06 06:58:36

As this question still gets a considerable amount of views 3 years later, I'll confirm here that the method given in the documentation sample works 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:

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

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

Maybe you must set content-type request property:

connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!