* HttpRequest.php

<?php
namespace et\http; /**
* Created by PhpStorm.
* User: mingzhanghui
* Date: 2018-09-18
* Time: 16:19
*/
class HttpRequest {
const BUFSIZE = ;
const DEFAULT_OPTIONS = [
'port' => ,
'timeout'=>
]; 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=, $timeout = ) {
$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 = , $size = ) {
$o = new \stdClass();
$o->query = new \stdClass();
$o->query->bool = new \stdClass();
$o->query->bool->must = [
=> ['match_phrase_prefix' => [
'request' => $uri
]],
=> ['range' => [
'@timestamp' => [
"gte"=> $begin,
"lte"=> $end,
"format"=> "yyyy-MM-dd HH:mm:ss"
]
]],
=> ['range' => [
'request_time' => ['gte' => $requestTime]
]]
];
$o->sort = [
=> [
'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",
, ); // post json
$response = et\http\HttpRequest::post(
'172.16.0.245',
'/filebeat-2018.09.12/_search?pretty',
$headers,
$body,
['port'=>]
); echo '<pre>';
print_r($response);

php socket 发送HTTP请求 POST json的更多相关文章

  1. 使用socket发送http请求(get/post)

    手动发送http请求 解释说明 https://blog.csdn.net/zhangliang_571/article/details/23508953 http://www.cnblogs.com ...

  2. c/c++ socket发送http请求访问网站

    这几天课比较少,校园网上网要认证才能上网,每次必须输入学号密码,为了方便,写了一个自动登录以及如果在线,登录自服务系统强制下线的小工具. 强制下线思路:获取sessionID----------> ...

  3. PHP + Socket 发送http请求进而实现站点灌水

    本质上实现组装http信息的请求行,头信息.主题信息.參考it自学网 cookie信息和http请求头有非常大关系,注意把http请求头信息传递到函数里面 01-msg.php <?php re ...

  4. Java发送Post请求,参数JSON,接收JSON

    /** * 发送post请求 * @param url 路径 * @param jsonObject 参数(json类型) * @param encoding 编码格式 * @return * @th ...

  5. 【C语言】Socket发送HTTP-TCP请求,数据有字符串插入

    问题描述: 场景:编写Socket接口,向LOKI发送POST请求查询数据 BUG发现位置:通过cJSON读取时间戳,发现被截断. 现象:通过read()去读取返回的数据,数据行中被插入字符:如下 c ...

  6. JAVA发送POST请求携带JSON格式字符串参数

    import org.apache.commons.lang.StringUtils; import org.apache.http.HttpEntity; import org.apache.htt ...

  7. Android Studio利用异步任务AsyncTask发送post请求获取json数据

    syncTask,是Android提供的轻量级的异步类,可以直接继承AsyncTask,在类中实现异步操作,并提供接口反馈当前异步执行的程度(可以通过接口实现UI进度更新),最后反馈执行的结果给UI主 ...

  8. linux c 使用socket 发送http请求 可以发送json格式数据

    #include <stdio.h>#include <sys/socket.h>#include <sys/types.h>#include <time.h ...

  9. 发送Ajax请求获取JSON格式数据

    Aspx前端页面: <script type="text/javascript"> $(function () { $.getJSON("Ajax/TestA ...

随机推荐

  1. strcmp 的坑

    根据百度百科的:http://baike.baidu.com/view/1026924.htm 函数简介 原型:extern int strcmp(const char *s1,const char ...

  2. Eclipse规范注释及注释文档的生成

    Eclipse作为JavaIDE(Integrated Development Environment,集成开发环境),可以通过设置自动添加Javadoc注释信息,如@author 作者名.@vers ...

  3. PHP headers_list() 函数

    定义和用法 headers_list() 函数返回已发送的(或待发送的)响应头部的一个列表. 该函数返回包含报头的数组. 语法 headers_list() 提示和注释 提示:如需确定是否已发送报头, ...

  4. hive中的lateral view 与 explode函数的使用

    hive中的lateral view 与 explode函数的使用 背景介绍: explode与lateral view在关系型数据库中本身是不该出现的. 因为他的出现本身就是在操作不满足第一范式的数 ...

  5. NX二次开发-UFUN获得当前图纸页有多少个视图UF_DRAW_ask_num_views

    #include <uf.h> #include <uf_draw.h> #include <uf_ui.h> UF_initialize(); //获得当前图纸页 ...

  6. (转)JAVA国际化

    转:http://www.cnblogs.com/jjtech/archive/2011/02/14/1954291.html 国际化英文单词为:Internationalization,又称I18N ...

  7. 数据结构C++版-图

    一.概念及分类 二.图的存储结构 1.邻接矩阵 顶点: 弧: 边: 表达式语句: 2.邻接表 逆邻接表: 3.十字链表 4.邻接多重表 三.图的权值概念及遍历 权值: 图的遍历: 1.深度优先搜索 2 ...

  8. Java-Class-I:java.util.Map

    ylbtech-Java-Class-I:java.util.Map 1.返回顶部 1.1. import java.util.HashMap; import java.util.Map; 1.2. ...

  9. BBB 常用指令

    source .bashrc root@beaglebone:~# route add default gw 192.168.7.1 echo BB-SPIDEV0 > /sys/devices ...

  10. 拾遗:Git 基础

    http://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c67b8067c8c017b000/ 一.参数配置 $ git con ...