zoukankan      html  css  js  c++  java
  • php发送http put/patch/delete请求

    今天学RESTful API的编写,发现不知道怎么发送HTTP PUT/PATCH/DELETE请求,还是要学习一个。
    使用curl_opt函数来发送各式各样的http请求动作,不仅限于get和post。
    在测试自己的restful api的时候,通过访问这个代理发送http put/patch/delete请求的php页面,完成测试。

    <?php
    /**
     * http.php
     * 用来向服务器的RESTful API发起各类HTTP请求的工具函数。
     *
     * 使用: http://mysite.com/http.php?action=xxx
     * xxx in {get,post,put,patch,delete}
     *
     * Created by PhpStorm.
     * User: chris
     * Date: 16/8/11
     * Time: 下午1:22
     */
    
    class commonFunction{
        function callInterfaceCommon($URL,$type,$params,$headers){
            $ch = curl_init($URL);
            $timeout = 5;
            if($headers!=""){
                curl_setopt ($ch, CURLOPT_HTTPHEADER, $headers);
            }else {
                curl_setopt ($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
            }
            curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
            switch ($type){
                case "GET" : curl_setopt($ch, CURLOPT_HTTPGET, true);break;
                case "POST": curl_setopt($ch, CURLOPT_POST,true);
                    curl_setopt($ch, CURLOPT_POSTFIELDS,$params);break;
                case "PUT" : curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PUT");
                    curl_setopt($ch, CURLOPT_POSTFIELDS,$params);break;
                case "PATCH": curl_setopt($ch, CULROPT_CUSTOMREQUEST, 'PATCH');
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $params);break;
                case "DELETE":curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
                    curl_setopt($ch, CURLOPT_POSTFIELDS,$params);break;
            }
            $file_contents = curl_exec($ch);//获得返回值
            return $file_contents;
            curl_close($ch);
        }
    }
    
    
    $params="{user:"admin",pwd:"admin"}";
    //$headers=array('Content-Type: text/html; charset=utf-8');
    //$headers=array('accept: application/json; Content-Type:application/json-patch+json');
    $headers=array('Content-Type:application/json-patch+json');
    #$url=$GLOBALS["serviceUrl"]."/user";
    $url='http://mysite.com/user/11';
    $cf = new commonFunction();
    
    $action=strtoupper($_GET['action']);
    echo "你指定的HTTP请求动作为".$action."<br/><hr/>";
    
    $strResult = $cf->callInterfaceCommon($url,$action,$params,$headers);
    echo "执行该HTTP请求动作,得到<br/>".$strResult;
    
  • 相关阅读:
    css3 rotate(1turn)的用法
    canvas svg webgl threejs d3js 的区别
    利用css3给座右铭设置漂亮的渐变色
    svg相关的知识
    Mark标记功能的实现(像手工标记的一样)
    终于搞清楚了正向代理与反向代理的区别
    获取免费ip_存入excel_用了线程池_封装清晰
    爬去京东——智能音箱
    滑动验证码
    天气爬取的笔记
  • 原文地址:https://www.cnblogs.com/zjutzz/p/php_send_http_put_patch_delete_action.html
Copyright © 2011-2022 走看看