代码之家  ›  专栏  ›  技术社区  ›  Andrea Sciamanna M4N

使用文件指针资源发送到RESTful服务JSON

  •  1
  • Andrea Sciamanna M4N  · 技术社区  · 12 年前

    我正在尝试如何通过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对象。 工作->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行所示,而不是发送URL编码的数据。

    有什么提示吗?

    1 回复  |  直到 12 年前
        1
  •  0
  •   Jørn Wildt    12 年前

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

    以下是来自 Mason 它试图将json/多部分用法形式化:

    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."
      }
    }