HTTP请求POST和GET的区别

3

我在编写一个使用OAuth的应用程序中使用了很多HTTP请求。目前,我以相同的方式发送我的GET和POST请求:

HttpConnection connection = (HttpConnection) Connector.open(url
                    + connectionParameters);

            connection.setRequestMethod(method);
            connection.setRequestProperty("WWW-Authenticate",
                    "OAuth realm=api.netflix.com");

            int responseCode = connection.getResponseCode();

这个工作得很好。我成功地进行了POST和GET操作。然而,我担心我没有正确地进行POST操作。在上面的代码中,我需要包含以下if语句吗?

if (method.equals("POST") && postData != null) {
                    connection.setRequestProperty("Content-type",
                            "application/x-www-form-urlencoded");
                    connection.setRequestProperty("Content-Length", Integer
                            .toString(postData.length));
                    OutputStream requestOutput = connection.openOutputStream();
                    requestOutput.write(postData);
                    requestOutput.close();
                }

如果是这样,为什么呢?有什么区别?我会非常感激任何反馈。
谢谢!
4个回答

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

内容类型必须与postData的实际格式匹配。只有当内容类型实际上是url编码时,才需要使用application/x-www-form-urlencoded的内容类型。例如,您可以按照以下方式对POST数据进行编码:

String data = "param1=" + URLEncoder.encode(param1, "UTF-8")
           + "&param2=" + URLEncoder.encode(param2, "UTF-8");

这样,另一方就可以根据指定的格式解析数据,而不会破坏它。

而且,

connection.setRequestProperty("Content-Length", Integer.toString(postData.length));

为确保数据传输的稳定性,最好进行此操作。如果您忽略此操作并且连接突然断开,则另一端将无法确定内容是否已完全流式传输。

话虽如此,如果您知道请求方法将“自动”设置为POST,则不必将其转换为HttpUrlConnection

connection.setDoOutput(true);

或者在你的情况下更加合适:

connection.setDoOutput("POST".equals(method));

谢谢,BalusC,这是一个非常有帮助的解释。 - littleK

3

来自HTML规范文档:

If the processing of a form is idempotent (i.e. it has no lasting observable effect on the state of the world), then the form method should be GET. Many database searches have no visible side-effects and make ideal applications of query forms. - -

If the service associated with the processing of a form has side effects

(for example, modification of a database or subscription to a service), the method should be POST.

它们大致相同,只是目的上有主要区别。

3

如果所访问的HTTP服务器需要,您需要设置内容类型标头。我们实际上无法知道是否需要。

如果您没有显式设置,内容长度标头应自动计算和设置,但是由于您事先已经知道它,因此我建议设置它,以便在实际发送数据之前HttpConnection不会不必要地缓冲您的内容。


2
使用POST请求来修改内容,使用GET请求来搜索或获取文档。在浏览器端的区别是,浏览器会避免意外地再次发送POST请求,例如通过提示用户进行确认。
处理POST请求时,永远不要响应文档,而是将用户重定向到包含“表单已提交”或其他想要提供的答案的GET请求中。这样可以避免浏览器的后退/前进按钮出现问题,否则浏览响应页面将需要重新提交POST请求。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接