Maison  >  Article  >  développement back-end  >  PHP implémente l'envoi de requêtes HTTP

PHP implémente l'envoi de requêtes HTTP

小云云
小云云original
2018-03-27 15:40:3414354parcourir

本文主要和大家分享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(&#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;

封装的方法:

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

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;
    }

           

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;

封装的请求方法

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;
    }

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(&#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;

封装的请求方法:

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;
    }

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(            &#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;

封装的方法:

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

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(&#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;

封装的方法:

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

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;
    }

相关推荐:

js如何实现发送http请求

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

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

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn