zoukankan      html  css  js  c++  java
  • php socket 发送HTTP请求 POST json

    * HttpRequest.php

    <?php
    namespace ethttp;
     
    /**
     * 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
    ", $uri));
            fwrite($socket, "User-Agent: Socket_Backstage
    ");
            fwrite($socket, sprintf("Content-length: %d
    ", strlen($body)));
            fwrite($socket, "Accept: */*
    ");
     
            self::mergeDefaultOptions($headers, self::DEFAULT_HEADRES);
            foreach ($headers as $name => $value) {
                fwrite($socket, $name.": ".$value."
    ");
            }
            fwrite($socket, "
    ");
     
            fwrite($socket, $body."
    ");
            fwrite($socket, "
    ");
     
            $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
    ", $uri, $qs));
            fwrite($socket, "User-Agent: Socket_Backstage
    ");
            fwrite($socket, "Content-type: application/x-www-form-urlencoded
    ");
            fwrite($socket, sprintf("Content-length: %d
    ", strlen($qs)));
            fwrite($socket, "Accept: */*
    ");
            fwrite($socket, "
    ");
            fwrite($socket, "
    ");
     
            $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 = ethttpHttpRequest::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 = ethttpHttpRequest::post(
        '172.16.0.245',
        '/filebeat-2018.09.12/_search?pretty',
        $headers,
        $body,
        ['port'=>9200]
    );
     
    echo '<pre>';
    print_r($response);
     
  • 相关阅读:
    Git笔记
    排序学习LTR(1):排序算法的评价指标
    C++指针
    C++基础知识笔记
    Shell脚本--菜鸟教程笔记
    torch学习01-入门文档学习
    torch学习02-tensor学习
    torch学习0: 学习概览
    linux基础-用户创建及管理相关
    python-getattr() 函数 dir() 函数
  • 原文地址:https://www.cnblogs.com/lxwphp/p/10031504.html
Copyright © 2011-2022 走看看