zoukankan      html  css  js  c++  java
  • guzzle 简单使用记录

    用 guzzle 发送一个包含指定请求头,请求体的 post 请求,并获取指定内容:

     1 <?php
     2 
     3 include_once "guzzle.phar";
     4 use GuzzleHttpClient;
     5 use GuzzleHttpPsr7Request;
     6 use PsrHttpMessageResponseInterface;
     7 
     8 $base_uri = "127.0.0.1:8082/";
     9 
    10 $method = "POST";//请求方式
    11 
    12 $data = array(
    13     "xxxx" => "xxx",
    14 );
    15 
    16 $headers = array(//添加请求头
    17     "Authorization" => " Basic " . base64_encode("testing:dhskln")
    18 );
    19 
    20 $options = array(//请求体
    21     "headers" => $headers,
    22     "body" => json_encode($data),
    23 );
    24 
    25 $send_request = new Client(["base_uri" => $base_uri]);
    26 
    27 $api = "host/test";
    28 
    29 $result = $send_request->request($method, $api, $options);
    30 
    31 print_r($result);
    32 
    33 $code = $result->getStatusCode(); // 获取响应码
    34 echo $code;
    35 $body = $result->getBody();//获取返回体
    36 echo $body;

    遇到的问题1:

    虽然代码中加了 use GuzzleHttpClient;,但是没有引用 guzzle.pahr 文件

    解决方法:在 use 前加上 include_once "guzzle.phar"; 即可

    遇到的问题2:

    body 没有使用 json 编码

    解决方法:

     

    详细的 guzzle 使用文档见:https://guzzle-cn.readthedocs.io/zh_CN/latest/quickstart.html

  • 相关阅读:
    Google 嘘! 嘘!
    zabbix fast
    zabbix
    kernel update
    列表推导
    Ddos 反射性防护 simple
    file cycle
    Scala
    Hadoop
    数据库
  • 原文地址:https://www.cnblogs.com/geloutingyu/p/9733196.html
Copyright © 2011-2022 走看看