我正在构建一个rest api服务器,我正在尝试将curl请求中的Content-Md5头发送到api服务器.我很困惑如何计算md5哈希发送请求发送和放?我们不需要GET和删除标题吗?
您不需要为任何不包含正文的请求提供标头.这意味着在实践中,假设使用简单的CRUD API,您只需要担心它PUT
和POST
请求,GET
并且DELETE
不需要包含它.
要包含的MD5哈希是通过将请求主体完整地传递给md5()
函数来计算的(在PHP中).使用cURL时,这意味着您必须手动将请求主体构造为字符串 - 您不能长时间将数组传递给CURLOPT_POSTFIELDS
.
让我们想象一下,我想将以下数组发送到服务器:
$array = array(
'thing' => 'stuff',
'other thing' => 'more stuff'
);
Run Code Online (Sandbox Code Playgroud)
如果我想将其作为JSON发布,我会做这样的事情:
$body = json_encode($array);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($body),
'Content-MD5: ' . base64_encode(md5($body, true))
));
// ...
Run Code Online (Sandbox Code Playgroud)
同样,如果我想发送它application/x-www-form-urlencoded
,我只需更改json_encode()
to http_build_query()
并更改Content-Type:
标题.
归档时间: |
|
查看次数: |
12382 次 |
最近记录: |