我将数据POSTing到外部应用程序接口(使用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);
发布于 2014-07-19 11:43:09
@DougW已经清楚地回答了这个问题,但我仍然想在这里添加一些代码来解释Doug的观点。(并更正上述代码中的错误)
解决方案1:使用内容类型标头对POST数据进行URL编码:application/x-www-form-urlencoded。
注意:您不需要一个接一个地对$_POST[]字段进行job编码,http_build_query()函数可以很好地完成job编码工作。
$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);
解决方案2:将数组作为post数据直接传递,不使用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);
这两个代码片段都可以工作,但使用了不同的HTTP头和主体。
发布于 2013-05-27 07:19:31
curl会为你编码数据,只需将你的原始字段数据放到字段数组中,并告诉它"go“。
发布于 2018-11-12 02:33:45
上面的帖子回答了与URL编码相关的问题以及它是如何工作的,但最初的问题是“我应该对帖子数据进行URL编码吗?”无人接听。
根据我最近使用URL编码的经验,我想进一步扩展这个问题。“我是否应该对POST数据进行URL编码,就像GET HTTP方法一样。通常,浏览器上的HTML表单如果被填写、提交和/或获取某些信息,浏览器将进行URL编码。但是,如果应用程序公开web服务并希望用户对数据进行URL编码,那么使用POST HTTP方法进行URL编码在体系结构上和技术上是否正确?”
https://stackoverflow.com/questions/6603928
复制相似问题