首页 > 解决方案 > 内容长度 PHP 标头。正确的计算方法

问题描述

我需要发送一个用 base64 编码的 XML 文件和一个变量中的其他数据$content。我不确定 Content-Length 是否以正确的方式计算,因为我的 web 服务告诉我有一个错误(无效的参数输入)。我确定发送的文件是正确的。所以我唯一的疑问是计算长度吗?

这是我的脚本:

$base64 = base64_encode(file_get_contents("file.xml"));

$post = "/services/invoice/upload";

$content = array(
    "dataFile" => $base64,
    "credential" => "",
    "domain" => ""
);

try {

    $ch = curl_init();

    $header = array(
        "Content-type: application/json;charset=UTF-8",
        "Accept: application/json",
        "Authorization: Bearer nfsedkvcsjocnso", //token
        "Content-Length:" . strlen(json_encode($content)), //
        "Host: localhost:8080"
      );

    curl_setopt($ch, CURLOPT_URL, "http://xxxxxxx.com" . $post);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($content));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    // receive server response



    $server_output = curl_exec($ch);

    if ($server_output === false) {
        throw new Exception(curl_error($ch), curl_errno($ch));
    }

    var_dump($server_output);

    curl_close($ch);

} catch(Exception $e) {

    trigger_error(sprintf('Curl failed with error #%d: %s',$e->getCode(), $e->getMessage()), E_USER_ERROR);

}

这是 WS 的规范(示例):

POST /services/invoice/upload HTTP/1.1
Accept: application/json
Authorization: Bearer NLOGDVXLVaF3tzmnVPkTwpkuh7dG0i09uSCcog3u+rE=
Content-Type: application/json;charset=UTF-8
Content-Length: 90
Host: localhost:8080

{
  "dataFile" : "dGVzdA==",
  "credential" : "cred_firma", //can be empty
  "domain" : "dom_firma" //can be empty
}

标签: php

解决方案


推荐阅读