0%

post 中 x-www-form-urlencoded 和 form-data

先说遇到的问题:

PHP调用后台接口时,指定使用POSTx-www-form-urlencoded方式。

首先想到的是传个header指定一下,搜索了一下发现的确是这样,设置CURLOPT_HTTPHEADER即可

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
但实际情况发现并不好使,然后Google一下这两者的区别吧。

post的两种Content-Type header的区别 - x-www-form-urlencoded 普通键值对 - form-data 要传输二进制(非字母数字)数据,例如文件

关于这两者的区别,stackoverflow有详细的解释,这里摘抄以下两段。

Summary; if you have binary (non-alphanumeric) data (or a significantly sized payload) to transmit, use multipart/form-data. Otherwise, use application/x-www-form-urlencoded.

摘要;如果您要传输二进制(非字母数字)数据(或有效载荷大小很大),请使用multipart/form-data。否则,请使用application/x-www-form-urlencoded

The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

内容类型application/x-www-form-urlencoded对于发送大量二进制数据或包含非ASCII字符的文本效率不高。内容类型multipart/form-data应用于提交包含文件,非ASCII数据和二进制数据的表单。

重点来了

对于application/x-www-form-urlencoded,发送到服务器的HTTP消息的主体实质上是一个巨大的查询字符串(键值对用=分隔,多个键值对用&分隔),即这种

title=aaa&name=bbb
所以很明显,要使用x-www-form-urlencoded的方式,CURLOPT_POSTFIELDS应该传如下这种使用http_build_query()转化后的内容
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('title' => 'aaa', 'name' => 'bbb')));
而不是类似直接传数组这种
curl_setopt($ch, CURLOPT_POSTFIELDS, array('title' => 'aaa', 'name' => 'bbb'));
更不是设置header

请我喝杯咖啡吧 Coffee time !