php socket 发送HTTP请求 POST json

php socket 发送HTTP请求 POST json

* 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);
 

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/112663.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号