1

我试图弄清楚如何通过 PHP 将这种数据发送到 RESTful 服务:

{
  "api_version": 1.0,
  "project_id" : 123,
  "batch_id" : 111,
  "accesskey" : "abc123",
  "job": {
    "file": file,
    "word_count": 111,
    "title": "FAQ",
    "cms_id": "page_123_en_sp",
    "url" : "http://original_post_url.com",
    "is_update": false, 
    "translator_id": 123,
    "note": "Translate these words",
    "source_language": "en",
    "target_language": "it"
  }
}

首先,我不能使用 curl,因为使用此代码的人可能没有安装它,或者可能不允许安装它。

这不是一个“正常”的 JSON 对象。job->file 属性是一个实际的文件(甚至不是文件的 url)。

这是我用来发送所有请求的实际代码并且它有效,直到我遇到这个特定情况: http: //pastebin.com/6pEjhAkg

'file' 属性是这样创建的:

$file = generate_file( $content );

protected static function generate_file($content) {
    $file = fopen('php://temp','r+');
    fwrite($file, $content);
    rewind($file);
    return $file;        
}

现在,当发送数据时,在 PHP 端正确设置了 $params 参数,RESTful 返回一个关于缺少 'api_version' 和 'project_id' 的错误,但它们存在。我很确定问题在于他没有以 JSON 格式接收数据,但是我如何将在他的属性中包含文件指针资源的对象转换为 JSON?

发送数据和构建文件的代码是由一位前开发人员创建的,我无法与他取得联系。

我试图了解那里出了什么问题,到目前为止,我设法解决的唯一问题是另一个不相关的问题,是实际发送 JSON 数据(当 $multipart==false 时),正如您在第 16-19 行中看到的那样链接代码,而不是发送 urlencoded 数据。

有什么提示吗?

4

1 回答 1

0

JSON 没有“文件”概念。您可以加载文件内容,使用 Base64 对其进行编码,然后将其填充到 JSON 字符串中 - 或者您可以使用多部分格式在一部分中发送文件,在另一部分中发送完整的 JSON。多部分解决方案应该是性能最好的,因为它不必对文件内容进行 base64 编码。

这是来自Mason的类似示例消息格式,它试图形式化 json/multipart 的用法:

POST /projects/2/issues HTTP/1.1
Accept: application/vnd.mason+json
Content-Type: multipart/form-data; boundary=d636dfda-b79f-4f29-aaf6-4b6687baebeb

--d636dfda-b79f-4f29-aaf6-4b6687baebeb
Content-Disposition: form-data; name="attachment"; filename="hogweed.jpg"
... binary data for attached image ...

--d636dfda-b79f-4f29-aaf6-4b6687baebeb
Content-Disposition: form-data; name="args"; filename="args"
Content-Type: application/json

{
  "Title": "Hogweeds on the plaza",
  "Description": "Could you please remove the hogweeds growing at the plaza?",
  "Severity": 5,
  "Attachment":
  {
    "Title": "Hogweed",
    "Description": "Photo of the hogweeds."
  }
}
于 2014-03-12T11:31:36.410 回答