欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

PHP实现发送HTTP请求

程序员文章站 2022-05-09 13:48:30
...

本文主要和大家分享PHP实现发送HTTP请求,主要以代码的形式和大家分享,希望能帮助到大家。

1 发送get请求

//测试do_get
    $url="http://localhost:8081/SpringMVC01/user/getUserInfoByGet/1.html";   
     $params=array('name'=>'张三');    $result=do_get($url,$params);    
     echo json_encode($result);    return;

封装的请求方法

function do_get($url, $params) {        $url = "{$url}?" . http_build_query ( $params );        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
        curl_setopt ( $ch, CURLOPT_TIMEOUT, 60 );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $params );        $result = curl_exec ( $ch );
        curl_close ( $ch );        return $result;
    }

Java模拟的接受端:

@ResponseBody
    @RequestMapping(value="/getUserInfoByGet/{userId}",method=RequestMethod.GET)    
    public Object getUserInfoByGet(@PathVariable("userId")Integer userId,@RequestParam("name")String name) {
        JSONObject user=new JSONObject();
        user.put("id", userId);
        user.put("name",name);        return user;
    }

2 发送POST请求

//测试do_post
    $url="http://localhost:8081/SpringMVC01/user/addUser.html";  
      $params=array('id'=>1,'name'=>'张三');    $headers=array(      
        "Content-Type:application/json;charset=utf-8",        
        "Accept:application/json;charset=utf-8"
    );    //json序列化
    $params=json_encode($params, JSON_FORCE_OBJECT);   
     $result=do_post($url,$params,$headers);    echo json_encode($result);    return;

封装的请求方法:

function do_post($url, $params, $headers) {
        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'POST' );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $params );
        curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
        curl_setopt ( $ch, CURLOPT_TIMEOUT, 60 );        $result = curl_exec ( $ch );
        curl_close ( $ch );        return $result;
    }

Java模拟的接收端:

@ResponseBody
    @RequestMapping(value="/addUser",method=RequestMethod.POST)   
     public Object addUser(@RequestBody User user) {
        System.out.println(user);        return user;
    }

3 发送文件到第三方
发送非二进制文件流

$file = $_FILES["file"];    
    $upload_file = array(            'type'  =>  $file['type'],           
     'name'  =>  $file['name'],            'file'  =>  $file['tmp_name'],
    );    $result=upload_file01($url, $params, $upload_file);    echo $result;

封装的方法:

// 上传文件 非二进制文件流
    function upload_file01($url, $params = array(), $upload_file = false) {
        $data = array ();        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'POST' );        if ($upload_file) { // 设置上传文件
            $file = new \CURLFile ( $upload_file ['file'], $upload_file ['type'], $upload_file ['name'] );            $params ['file'] = $file;
        }
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $params );        $result = curl_exec ( $ch );
        curl_close ( $ch );        $data = json_decode ( $result, true );        return $data;
    }

Java模拟接收端

@RequestMapping(value = "/uploadFile01")
    @ResponseBody    public Object uploadFile01(HttpServletRequest request, HttpServletResponse response,
            @RequestParam(value = "file", required = true) MultipartFile file, @RequestParam Map<String,Object> params) {        try {
            FileOutputStream fileOutputStream = new FileOutputStream("D:\\" + file.getOriginalFilename());            byte[] bytes = file.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(fileOutputStream);
            stream.write(bytes);
            stream.close();
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("上传完成");        return params;
    }

发送二进制流

//测试upload_file
    $url="http://localhost:8081/SpringMVC01/file/uploadFile02.html";    $params=array('id'=>1,'name'=>'张三');    $file = $_FILES["file"];    
    $headers = array (            "Content-type:application/octet-stream",            "Accept:application/json;"
    );    $result=upload_file02($url, $params, $file['tmp_name'],$headers);    echo $result;

封装的方法:

// 上传文件,二进制文件流的形式
    function upload_file02($url, $params, $file_path, $headers) {
        $ch = curl_init ();        $url = "{$url}?" . http_build_query ( $params ); // 构造url
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'POST' );
        curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
        curl_setopt ( $ch, CURLOPT_TIMEOUT, 60 );        $file_data = '';        if ($file_path) { // 设置上传文件
            $fh = fopen ( $file_path, 'r' );            $file_data = fread ( $fh, filesize ( $file_path ) );
            fclose ( $fh );
        }
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $file_data );        $result = curl_exec ( $ch );
        curl_close ( $ch );        return $result;
    }

Java模拟接收端:

// 上传文件,二进制文件流的形式
    function upload_file02($url, $params, $file_path, $headers) {
        $ch = curl_init ();        $url = "{$url}?" . http_build_query ( $params ); // 构造url
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'POST' );
        curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
        curl_setopt ( $ch, CURLOPT_TIMEOUT, 60 );        $file_data = '';        if ($file_path) { // 设置上传文件
            $fh = fopen ( $file_path, 'r' );            $file_data = fread ( $fh, filesize ( $file_path ) );
            fclose ( $fh );
        }
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $file_data );        $result = curl_exec ( $ch );
        curl_close ( $ch );        return $result;
    }

1 发送get请求

//测试do_get
    $url="http://localhost:8081/SpringMVC01/user/getUserInfoByGet/1.html";    $params=array('name'=>'张三');    $result=do_get($url,$params);    echo json_encode($result);    return;

封装的请求方法

function do_get($url, $params) {        $url = "{$url}?" . http_build_query ( $params );        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
        curl_setopt ( $ch, CURLOPT_TIMEOUT, 60 );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $params );        $result = curl_exec ( $ch );
        curl_close ( $ch );        return $result;
    }

Java模拟的接受端:

@ResponseBody
    @RequestMapping(value="/getUserInfoByGet/{userId}",method=RequestMethod.GET)    public Object getUserInfoByGet(@PathVariable("userId")Integer userId,@RequestParam("name")String name) {
        JSONObject user=new JSONObject();
        user.put("id", userId);
        user.put("name",name);        return user;
    }

2 发送POST请求

//测试do_post
    $url="http://localhost:8081/SpringMVC01/user/addUser.html";    $params=array('id'=>1,'name'=>'张三');    $headers=array(        "Content-Type:application/json;charset=utf-8",        "Accept:application/json;charset=utf-8"
    );    //json序列化
    $params=json_encode($params, JSON_FORCE_OBJECT);    $result=do_post($url,$params,$headers);    echo json_encode($result);    return;

封装的请求方法:

function do_post($url, $params, $headers) {
        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'POST' );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $params );
        curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
        curl_setopt ( $ch, CURLOPT_TIMEOUT, 60 );        $result = curl_exec ( $ch );
        curl_close ( $ch );        return $result;
    }

Java模拟的接收端:

@ResponseBody
    @RequestMapping(value="/addUser",method=RequestMethod.POST)    public Object addUser(@RequestBody User user) {
        System.out.println(user);        return user;
    }

3 发送文件到第三方
发送非二进制文件流

$file = $_FILES["file"];    
    $upload_file = array(            'type'  =>  $file['type'],            'name'  =>  $file['name'],            'file'  =>  $file['tmp_name'],
    );    $result=upload_file01($url, $params, $upload_file);    echo $result;

封装的方法:

// 上传文件 非二进制文件流
    function upload_file01($url, $params = array(), $upload_file = false) {
        $data = array ();        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'POST' );        if ($upload_file) { // 设置上传文件
            $file = new \CURLFile ( $upload_file ['file'], $upload_file ['type'], $upload_file ['name'] );            $params ['file'] = $file;
        }
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $params );        $result = curl_exec ( $ch );
        curl_close ( $ch );        $data = json_decode ( $result, true );        return $data;
    }

Java模拟接收端

@RequestMapping(value = "/uploadFile01")
    @ResponseBody    public Object uploadFile01(HttpServletRequest request, HttpServletResponse response,
            @RequestParam(value = "file", required = true) MultipartFile file, @RequestParam Map<String,Object> params) {        try {
            FileOutputStream fileOutputStream = new FileOutputStream("D:\\" + file.getOriginalFilename());            byte[] bytes = file.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(fileOutputStream);
            stream.write(bytes);
            stream.close();
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("上传完成");        return params;
    }

发送二进制流

//测试upload_file
    $url="http://localhost:8081/SpringMVC01/file/uploadFile02.html";    $params=array('id'=>1,'name'=>'张三');    $file = $_FILES["file"];    
    $headers = array (            "Content-type:application/octet-stream",            "Accept:application/json;"
    );    $result=upload_file02($url, $params, $file['tmp_name'],$headers);    echo $result;

封装的方法:

// 上传文件,二进制文件流的形式
    function upload_file02($url, $params, $file_path, $headers) {
        $ch = curl_init ();        $url = "{$url}?" . http_build_query ( $params ); // 构造url
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'POST' );
        curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
        curl_setopt ( $ch, CURLOPT_TIMEOUT, 60 );        $file_data = '';        if ($file_path) { // 设置上传文件
            $fh = fopen ( $file_path, 'r' );            $file_data = fread ( $fh, filesize ( $file_path ) );
            fclose ( $fh );
        }
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $file_data );        $result = curl_exec ( $ch );
        curl_close ( $ch );        return $result;
    }

Java模拟接收端:

// 上传文件,二进制文件流的形式
    function upload_file02($url, $params, $file_path, $headers) {
        $ch = curl_init ();        $url = "{$url}?" . http_build_query ( $params ); // 构造url
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'POST' );
        curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
        curl_setopt ( $ch, CURLOPT_TIMEOUT, 60 );        $file_data = '';        if ($file_path) { // 设置上传文件
            $fh = fopen ( $file_path, 'r' );            $file_data = fread ( $fh, filesize ( $file_path ) );
            fclose ( $fh );
        }
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $file_data );        $result = curl_exec ( $ch );
        curl_close ( $ch );        return $result;
    }

相关推荐:

js如何实现发送http请求

几种PHP发送HTTP请求的方式分享

php如何通过http请求发送数组的实例分享

以上就是PHP实现发送HTTP请求的详细内容,更多请关注其它相关文章!

相关标签: HTTP php 请求