Ric*_*ard 119 post http urlencode http-post url-encoding
我正在将数据发布到外部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);
Run Code Online (Sandbox Code Playgroud)
Dou*_*ugW 132
你的问题的一般答案是它取决于.您可以通过指定HTTP标头中的"Content-Type"来决定.
值"application/x-www-form-urlencoded"表示您的POST主体需要像GET参数字符串一样进行URL编码.值"multipart/form-data"表示您将使用内容分隔符而不是url编码内容.
如果您想了解更多信息,这个答案有更全面的解释.
有关您正在使用的PHP库(CURL)的特定答案,请阅读此处的文档.
这是相关信息:
CURLOPT_POST
是的,以执行常规HTTP POST.此POST是普通的application/x-www-form-urlencoded类型,最常用于HTML表单.
CURLOPT_POSTFIELDS
要在HTTP"POST"操作中发布的完整数据.要发布文件,请在文件前加上@并使用完整路径.可以通过使用格式为'; type = mimetype'的类型的文件名来明确指定文件类型.此参数可以作为urlencoded字符串传递,如'para1 = val1¶2 = val2&...',也可以作为数组传递,字段名称为键,字段数据为值.如果value是数组,则Content-Type标头将设置为multipart/form-data.从PHP 5.2.0开始,如果使用@前缀将文件传递给此选项,则value必须是数组.
@DougW清楚地回答了这个问题,但我仍然想在这里添加一些代码来解释道格的观点.(并纠正上面代码中的错误)
解决方案1:使用内容类型标头对POST数据进行URL编码:application/x-www-form-urlencoded.
注意:你不需要逐个urlencode $ _POST []字段,http_build_query()函数可以很好地完成urlencoding工作.
$fields = array(
'mediaupload'=>$file_field,
'username'=>$_POST["username"],
'password'=>$_POST["password"],
'latitude'=>$_POST["latitude"],
'longitude'=>$_POST["longitude"],
'datetime'=>$_POST["datetime"],
'category'=>$_POST["category"],
'metacategory'=>$_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,1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
Run Code Online (Sandbox Code Playgroud)
解决方案2:直接将数组作为发布数据传递而不进行URL编码,而Content-Type标题将设置为multipart/form-data.
$fields = array(
'mediaupload'=>$file_field,
'username'=>$_POST["username"],
'password'=>$_POST["password"],
'latitude'=>$_POST["latitude"],
'longitude'=>$_POST["longitude"],
'datetime'=>$_POST["datetime"],
'category'=>$_POST["category"],
'metacategory'=>$_POST["metacategory"],
'caption'=>$_POST["description"]
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
Run Code Online (Sandbox Code Playgroud)
两个代码段都有效,但使用不同的HTTP标头和正文.
| 归档时间: |
|
| 查看次数: |
159441 次 |
| 最近记录: |