PHP implements sending HTTP requests

小云云
Release: 2023-03-22 13:08:01
Original
14350 people have browsed it

本文主要和大家分享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;
Copy after login

封装的请求方法

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;
    }
Copy after login
Copy after login

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;
    }
Copy after login

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;
Copy after login

封装的请求方法:

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;
    }
Copy after login
Copy after login

Java模拟的接收端:

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

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;
Copy after login

封装的方法:

// 上传文件 非二进制文件流
    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;
    }
Copy after login
Copy after login

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;
    }
Copy after login
Copy after login

发送二进制流

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

封装的方法:

// 上传文件,二进制文件流的形式
    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, &#39;POST&#39; );
        curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
        curl_setopt ( $ch, CURLOPT_TIMEOUT, 60 );        $file_data = &#39;&#39;;        if ($file_path) { // 设置上传文件
            $fh = fopen ( $file_path, &#39;r&#39; );            $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;
    }
Copy after login
Copy after login
Copy after login
Copy after login

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, &#39;POST&#39; );
        curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
        curl_setopt ( $ch, CURLOPT_TIMEOUT, 60 );        $file_data = &#39;&#39;;        if ($file_path) { // 设置上传文件
            $fh = fopen ( $file_path, &#39;r&#39; );            $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;
    }
Copy after login
Copy after login
Copy after login
Copy after login

1 发送get请求

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

封装的请求方法

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, &#39;GET&#39; );
        curl_setopt ( $ch, CURLOPT_TIMEOUT, 60 );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $params );        $result = curl_exec ( $ch );
        curl_close ( $ch );        return $result;
    }
Copy after login
Copy after login

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;
    }
Copy after login

2 发送POST请求

//测试do_post
    $url="http://localhost:8081/SpringMVC01/user/addUser.html";    $params=array(&#39;id&#39;=>1,&#39;name&#39;=>&#39;张三&#39;);    $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;
Copy after login

封装的请求方法:

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, &#39;POST&#39; );
        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;
    }
Copy after login
Copy after login

Java模拟的接收端:

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

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

$file = $_FILES["file"];    
    $upload_file = array(            &#39;type&#39;  =>  $file[&#39;type&#39;],            &#39;name&#39;  =>  $file[&#39;name&#39;],            &#39;file&#39;  =>  $file[&#39;tmp_name&#39;],
    );    $result=upload_file01($url, $params, $upload_file);    echo $result;
Copy after login

封装的方法:

// 上传文件 非二进制文件流
    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, &#39;POST&#39; );        if ($upload_file) { // 设置上传文件
            $file = new \CURLFile ( $upload_file [&#39;file&#39;], $upload_file [&#39;type&#39;], $upload_file [&#39;name&#39;] );            $params [&#39;file&#39;] = $file;
        }
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $params );        $result = curl_exec ( $ch );
        curl_close ( $ch );        $data = json_decode ( $result, true );        return $data;
    }
Copy after login
Copy after login

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;
    }
Copy after login
Copy after login

发送二进制流

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

封装的方法:

// 上传文件,二进制文件流的形式
    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, &#39;POST&#39; );
        curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
        curl_setopt ( $ch, CURLOPT_TIMEOUT, 60 );        $file_data = &#39;&#39;;        if ($file_path) { // 设置上传文件
            $fh = fopen ( $file_path, &#39;r&#39; );            $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;
    }
Copy after login
Copy after login
Copy after login
Copy after login

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, &#39;POST&#39; );
        curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
        curl_setopt ( $ch, CURLOPT_TIMEOUT, 60 );        $file_data = &#39;&#39;;        if ($file_path) { // 设置上传文件
            $fh = fopen ( $file_path, &#39;r&#39; );            $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;
    }
Copy after login
Copy after login
Copy after login
Copy after login

相关推荐:

js如何实现发送http请求

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

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

The above is the detailed content of PHP implements sending HTTP requests. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!