Rumah > pembangunan bahagian belakang > tutorial php > PHP实现发送HTTP请求

PHP实现发送HTTP请求

小云云
Lepaskan: 2023-03-22 13:08:01
asal
14384 orang telah melayarinya

本文主要和大家分享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;
Salin selepas log masuk

封装的请求方法

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;
    }
Salin selepas log masuk
Salin selepas log masuk

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;
    }
Salin selepas log masuk

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;
Salin selepas log masuk

封装的请求方法:

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;
    }
Salin selepas log masuk
Salin selepas log masuk

Java模拟的接收端:

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

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;
Salin selepas log masuk

封装的方法:

// 上传文件 非二进制文件流
    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;
    }
Salin selepas log masuk
Salin selepas log masuk

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;
    }
Salin selepas log masuk
Salin selepas log masuk

发送二进制流

//测试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;
Salin selepas log masuk
Salin selepas log masuk

封装的方法:

// 上传文件,二进制文件流的形式
    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;
    }
Salin selepas log masuk
Salin selepas log masuk
Salin selepas log masuk
Salin selepas log masuk

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;
    }
Salin selepas log masuk
Salin selepas log masuk
Salin selepas log masuk
Salin selepas log masuk

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;
Salin selepas log masuk

封装的请求方法

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;
    }
Salin selepas log masuk
Salin selepas log masuk

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;
    }
Salin selepas log masuk

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;
Salin selepas log masuk

封装的请求方法:

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;
    }
Salin selepas log masuk
Salin selepas log masuk

Java模拟的接收端:

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

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;
Salin selepas log masuk

封装的方法:

// 上传文件 非二进制文件流
    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;
    }
Salin selepas log masuk
Salin selepas log masuk

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;
    }
Salin selepas log masuk
Salin selepas log masuk

发送二进制流

//测试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;
Salin selepas log masuk
Salin selepas log masuk

封装的方法:

// 上传文件,二进制文件流的形式
    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;
    }
Salin selepas log masuk
Salin selepas log masuk
Salin selepas log masuk
Salin selepas log masuk

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;
    }
Salin selepas log masuk
Salin selepas log masuk
Salin selepas log masuk
Salin selepas log masuk

相关推荐:

js如何实现发送http请求

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

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

Atas ialah kandungan terperinci PHP实现发送HTTP请求. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Label berkaitan:
sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan