php发送http put/patch/delete请求Demo

栏目: PHP · 发布时间: 8年前

内容简介:php发送http put/patch/delete请求Demo

CURL请求对于PHPer是必备技能,使用 curl_opt 函数来发送各式各样的http请求动作,不仅限于get和post。

在测试自己的restful api的时候,通过访问这个代理发送http put/patch/delete请求的 php 页面,完成测试。请参考下面的DEMO。

<?php
/**
 * http.php
 * 用来向服务器的RESTful API发起各类HTTP请求的 工具 函数。
 *
 * 使用: http://localhost/http.php?action=xxx
 * xxx \in {get,post,put,patch,delete}
 *
 * Created by PhpStorm.
 * User: Lenix
 * Date: 2018/1/6
 * Time: 下午20:22
 */

class commonFunction{
    public function callInterfaceCommon(string $URL, string $type, string $params, array $headers):string {
        $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://localhost/action.php';
$cf = new commonFunction();

$action=strtoupper($_GET['action']);
echo "你指定的HTTP请求动作为".$action."<br/><hr/>";

$strResult = $cf->callInterfaceCommon($url,$action,$params,$headers);
echo "执行该HTTP请求动作,得到<br/>".$strResult;

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Beginning ASP.NET 4 in C# and Vb

Beginning ASP.NET 4 in C# and Vb

Imar Spaanjaars / Wrox / 2010-3-19 / GBP 29.99

This book is for anyone who wants to learn how to build rich and interactive web sites that run on the Microsoft platform. With the knowledge you gain from this book, you create a great foundation to ......一起来看看 《Beginning ASP.NET 4 in C# and Vb》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

MD5 加密
MD5 加密

MD5 加密工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换