代码之家  ›  专栏  ›  技术社区  ›  user1032531

使用cURL使用内容类型发送数据和文件:application/json

  •  2
  • user1032531  · 技术社区  · 7 年前

    下面将使用cURL发送数据以及使用 content-type application/x-www-form-urlencoded

    我不想用 Content-Type: application/x-www-form-urlencoded 但是用 Content-Type: application/json .

    内容类型:application/json .

    内容类型:application/json ?

    以下代码x-www-form-urlencoded仅供参考

    <?php
    //Given:
    $method='post';
    $url='http://php.net/manual/en/function.curl-setopt.php';
    $data=['hello'=>123];
    $files=["image"=>["name" => "picture.jpg","type" => "image/jpeg","tmp_name" => "/path/on/server/to/tmp/phprj5rkG","error" => 0,"size" => 174476]];
    
    //For using content-type application/x-www-form-urlencoded
    
    $postData = [];
    if($files) {
        //cURL doesn't work out of the box with both files and POST data.
        foreach ($files as $name=>$file){
            $postData[$name] = new \CURLFile($file['tmp_name'],$file['type'],$file['name']);
        }
        if($data) {
            foreach (explode('&', http_build_query($data)) as $pair){
                list($name, $value) = explode('=', $pair, 2);
                $postData[urldecode($name)] = urldecode($value);
            }
        }
    }
    else {
        $postData=http_build_query($data);
    }
    
    $options=[
        CURLOPT_RETURNTRANSFER => true,     // return web page
        CURLOPT_HEADER         => false,    // don't return headers
        CURLOPT_FOLLOWLOCATION => true,     // follow redirects
        CURLOPT_ENCODING       => "",       // handle all encodings
        CURLOPT_AUTOREFERER    => true,     // set referrer on redirect
    ];
    switch ($method) {
        case "get":
            if ($postData) {$url = sprintf("%s?%s", $url, $postData);}
            break;
        case "post":
            $options[CURLOPT_POST]=1;
            $options[CURLOPT_POSTFIELDS]=$postData?$postData:'';
            break;
        case "put":
            $options[CURLOPT_CUSTOMREQUEST]="PUT";
            if ($postData) {$options[CURLOPT_POSTFIELDS]=$postData;}
            break;
        case "delete":
            $options[CURLOPT_CUSTOMREQUEST]="DELETE";
            if ($postData) {$options[CURLOPT_POSTFIELDS]=$postData;}
            break;
    }
    $options[CURLOPT_URL]=$url;
    $ch      = curl_init();
    curl_setopt_array( $ch, $options );
    
    $rsp=curl_exec( $ch );
    
    0 回复  |  直到 7 年前