php socket 发送HTTP请求 POST json

举报
lxw1844912514 发表于 2022/03/27 02:28:48 2022/03/27
【摘要】 * HttpRequest.php <?php namespace et\http; /** * Created by PhpStorm. * User: mingzhanghui * Date: 2018-09-18 * Time: 16:19 */ class HttpRequest { ...

* HttpRequest.php

<?php
namespace et\http;
 
/**
 * Created by PhpStorm.
 * User: mingzhanghui
 * Date: 2018-09-18
 * Time: 16:19
 */
class HttpRequest {
    const BUFSIZE = 4096;
    const DEFAULT_OPTIONS = [
        'port' => 80,
        'timeout'=> 30
    ];
 
    const DEFAULT_HEADRES = [
        'Content-Type' => 'application/x-www-form-urlencoded'
    ];
 
    public static function mergeDefaultOptions(Array& $to, Array $default) {
        foreach ($default as $key => $value) {
            if (!array_key_exists($key, $to)) {
                $to[$key] = $value;
            }
        }
    }
 
    /**
     * @param $host string remote server '192.168.1.219:7102' without http://
     * @param $uri string remote uri '/service/pageinfo/'
     * @param $headers
     * @param string $body
     * @param array $options
     * @return string
     * @throws \Exception
     */
    public static function post($host, $uri, $headers = [], $body = "", $options = []) {
        self::mergeDefaultOptions($options, self::DEFAULT_OPTIONS);
 
        $socket = fsockopen($host, $options['port'], $errno, $errstr, $options['timeout']);
        if (!$socket) {
            throw new \Exception(sprintf("%s(%d)", $errstr, $errno));
        }
 
        fwrite($socket, sprintf("POST %s HTTP/1.0\r\n", $uri));
        fwrite($socket, "User-Agent: Socket_Backstage\r\n");
        fwrite($socket, sprintf("Content-length: %d\r\n", strlen($body)));
        fwrite($socket, "Accept: */*\r\n");
 
        self::mergeDefaultOptions($headers, self::DEFAULT_HEADRES);
        foreach ($headers as $name => $value) {
            fwrite($socket, $name.": ".$value."\r\n");
        }
        fwrite($socket, "\r\n");
 
        fwrite($socket, $body."\r\n");
        fwrite($socket, "\r\n");
 
        $header = "";
        while ($str = trim(fgets($socket, self::BUFSIZE))) {
            $header .= $str;
        }
        $resp = "";
        while (!feof($socket)) {
            $resp .= fgets($socket, self::BUFSIZE);
        }
        return $resp;
    }
 
    public static function get($host, $uri, $data, $port=80, $timeout = 30) {
        $socket = fsockopen($host, $port, $errno, $errstr, $timeout);
        if (!$socket) {
            throw new \Exception(sprintf("%s(%d)", $errstr, $errno));
        }
        $qs = http_build_query($data, '', '&');
 
        fwrite($socket, sprintf("GET %s?%s HTTP/1.0\r\n", $uri, $qs));
        fwrite($socket, "User-Agent: Socket_Backstage\r\n");
        fwrite($socket, "Content-type: application/x-www-form-urlencoded\r\n");
        fwrite($socket, sprintf("Content-length: %d\r\n", strlen($qs)));
        fwrite($socket, "Accept: */*\r\n");
        fwrite($socket, "\r\n");
        fwrite($socket, "\r\n");
 
        $header = "";
        while ($str = trim(fgets($socket, self::BUFSIZE))) {
            $header .= $str;
        }
        $resp = "";
        while (!feof($socket)) {
            $resp .= fgets($socket, self::BUFSIZE);
        }
        return $resp;
    }
 
    /**
     * $.post(url, data, function(data) { ... })
     * @param $url
     * @param $data
     * @return mixed
     * @throws \Exception
     */
    public static function post_url($url, Array $data) {
        $components = parse_url($url);
        if ($components === false) {
            throw new \Exception('url is not valid');
        }
        if ($components['scheme'] != 'http') {
            throw new \Exception('scheme is not http');
        }
        $host = $components['host'];
        $path = empty($components['path']) ? '/' : $components['path'];
 
        $headers = [
            'Content-Type' => 'application/x-www-form-urlencoded'
        ];
        $body = http_build_query($data, '', '&');
 
        return self::post($host, $path, $headers, $body, self::DEFAULT_OPTIONS);
    }
}

* test

index.php

<?php
/**
 * Created by PhpStorm.
 * User: mingzhanghui
 * Date: 2018-09-18
 * Time: 10:46
 */
include 'HttpRequest.php';
 
// $response = \et\http\HttpRequest::get('www.baidu.com', '/', []);
// $body = http_build_query($data, '', '&');
 
$headers = ['Content-Type' => 'application/json'];
// $body = "{\"query\":{\"bool\":{\"must\":[{\"match_phrase_prefix\":{\"request\":\"/cgi-bin/service\"}},{\"range\":{\"@timestamp\":{\"gte\":\"2017-09-11 09:26:10\",\"lte\":\"2018-09-13 09:27:10\",\"format\":\"yyyy-MM-dd HH:mm:ss\"}}},{\"range\":{\"request_time\":{\"gte\":5}}}]}},\"sort\":[{\"request_time\":{\"order\":\"desc\"}}],\"size\":10}";
 
function buildQueryBodySlow($uri, $begin, $end, $requestTime = 5, $size = 10) {
    $o = new \stdClass();
    $o->query = new \stdClass();
    $o->query->bool = new \stdClass();
    $o->query->bool->must = [
        0 => ['match_phrase_prefix' => [
            'request' => $uri
        ]],
        1 => ['range' => [
            '@timestamp' => [
                "gte"=> $begin,
                "lte"=> $end,
                "format"=> "yyyy-MM-dd HH:mm:ss"
            ]
        ]],
        2 => ['range' => [
            'request_time' => ['gte' => $requestTime]
        ]]
    ];
    $o->sort = [
        0 => [
            'request_time'=> [
                'order'=>'desc'
            ]
        ]
    ];
    $o->size = $size;
 
    return json_encode($o);
}
 
$body = buildQueryBodySlow(
    '/cgi-bin/service',
    "2017-09-11 09:26:10",
    "2018-09-13 09:27:10",
    5,
    1
);
 
// post json
$response = et\http\HttpRequest::post(
    '172.16.0.245',
    '/filebeat-2018.09.12/_search?pretty',
    $headers,
    $body,
    ['port'=>9200]
);
 
echo '<pre>';
print_r($response);
 

 

文章来源: blog.csdn.net,作者:lxw1844912514,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/lxw1844912514/article/details/100027761

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。