我正在将数据发布到外部 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¶2=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/