sending xml and headers via curl

前端 未结 1 2051
暖寄归人
暖寄归人 2020-12-11 22:42

wondering how I can set all this data in a curl session, via php:

POST /feeds/api/users/default/uploads HTTP/1.1
Host: uploads.gdata.youtube.com
Authorizatio         


        
相关标签:
1条回答
  • 2020-12-11 22:49

    The boundary is required because the form enctype is multipart/form-data, rather in this case multipart/related. The boundary is a unique string that cannot appear anywhere else in the request, and it is used to separate each element from the form, whether it is the value of a text input, or a file upload. Each boundary has its own content-type.

    Curl cannot do multipart/related for you, so you will need to use a workaround, see this message from the curl mailing list for suggestions. Basically, you will have to construct most of the message yourself.

    Note, the last boundary has an additional -- at the end.

    This code should hopefully help get you started:

    <?php
    
    $url       = 'http://uploads.gdata.youtube.com/feeds/api/users/default/uploads';
    $authToken = 'DXAA...sdb8'; // token you got from google auth
    $boundary  = uniqid();      // generate uniqe boundary
    $headers   = array("Content-Type: multipart/related; boundary=\"$boundary\"",
                       "Authorization: AuthSub token=\"$authToken\"",
                       'GData-Version: 2',
                       'X-GData-Key: key=adf15....a8dc',
                       'Slug: video-test.mp4');
    
    $postData  = "--$boundary\r\n"
                ."Content-Type: application/atom+xml; charset=UTF-8\r\n\r\n"
                .$xmlString . "\r\n"  // this is the xml atom data
                ."--$boundary\r\n"
                ."Content-Type: video/mp4\r\n"
                ."Content-Transfer-Encoding: binary\r\n\r\n"
                .$videoData . "\r\n"  // this is the content of the mp4
                ."--$boundary--";
    
    
    $ch  = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    
    $response = curl_exec($ch);
    curl_close($ch);
    

    Hope that helps.

    0 讨论(0)
提交回复
热议问题