http - 我应该对 POST 数据进行 URL 编码吗?

标签 http post http-post urlencode

我正在将数据发布到外部 API(如果相关,则使用 PHP)。

我应该对传递的 POST 变量进行 URL 编码吗?

还是我只需要对 GET 数据进行 URL 编码?


更新:这是我的 PHP,以防相关:

$fields = array(
    'mediaupload'=>$file_field,
    'username'=>urlencode($_POST["username"]),
    'password'=>urlencode($_POST["password"]),
    'latitude'=>urlencode($_POST["latitude"]),
    'longitude'=>urlencode($_POST["longitude"]),
    'datetime'=>urlencode($_POST["datetime"]),
    'category'=>urlencode($_POST["category"]),
    'metacategory'=>urlencode($_POST["metacategory"]),
    'caption'=>($_POST["description"])
);
$fields_string = http_build_query($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);

最佳答案

一般答案

您问题的一般答案是视情况而定。您可以通过在 HTTP header 中指定您的“Content-Type”来决定。

“application/x-www-form-urlencoded”的值意味着您的 POST 正文需要像 GET 参数字符串一样进行 URL 编码。 “multipart/form-data”的值意味着您将使用内容定界符而不是对内容进行 url 编码。

This answer has a much more thorough explanation如果您想了解更多信息。


具体答案

对于特定于您正在使用的 PHP 库的答案 (CURL),您应该 read the documentation here .

相关信息如下:

CURLOPT_POST

TRUE to do a regular HTTP POST. This POST is the normal application/x-www-form-urlencoded kind, most commonly used by HTML forms.

CURLOPT_POSTFIELDS

The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'. This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data. As of PHP 5.2.0, value must be an array if files are passed to this option with the @ prefix.

关于http - 我应该对 POST 数据进行 URL 编码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6603928/

相关文章:

http - 实际web开发中http协议(protocol)还剩下什么?

node.js - 自相矛盾的 CORS 错误 : Either no 'Access-Control-Allow-Origin' present OR 'Access-Control-Allow-Origin' header contains multiple values

javascript - 如何使用 POST 方法检索另一个 php 文件中动态创建文本框的文本?

ios - 发布请求后发回回复

php - 具有长 URI 的 Android HttpPost

javascript - 将文件发布到带有 Node 的 url

rest - 使用 WifiESP 库对带有 ESP8266 的 arduino 进行 POST 请求

javascript - 用于跟踪 HTTP 请求来源的 JS/Web 调试器?

c - 如何删除此 HEADER HTTP?

http - WebLogic 为空的主机 header 请求返回 Bad Request