$data= "username=zhangsan&age=8"; $len =strlen($data); //print_r($len);die; $errornu = -1; $errstr = ''; $url= 'http://localhost/socket/post.php'; $fh = parse_url($url); //print_r($fh);die; if(!isset($fh['port'])){ $fh['port'] = 80; } $conn = fsockopen($fh['host'],$fh['port'],$errornu,$errstr,3); //print_r($conn);die; if(!$conn){
echo " $errstr ( $errnu )<br />\n" ;
}else{
$post = 'POST '.$fh['path'].' HTTP/1.1'."\r\n";
$post .= 'Host: '.$fh['host']."\r\n";
$post .= 'Content-type: application/x-www-form-urlencoded'."\r\n";
$post .= 'Content-length:'.' '.$len."\r\n";
$post .= ' '."\r\n";
$post .=$data."\r\n";
$post .= ' '."\r\n";
$post .= "Connection: Close\r\n\r\n" ;
//echo $post;die;
fwrite($conn,$post);
while(!feof($conn)){
echo fread ( $conn ,128 );
}
fclose($conn);
}
怎么都是出现 400 的错误,希望大神帮我看看,是怎么回事?
1
coltguo OP <?php
/** * Created by PhpStorm. * User: kobe * Date: 2017/6/23 * Time: 上午 9:40 */ //print_r($_POST); $str = implode('/n',$_POST); file_put_contents('1.txt',$str); echo 'write ok'; |
2
coltguo OP 这是 post 文件
|
3
suchasplus 2017-06-27 22:51:46 +08:00 via Android
试试 curl
|
4
chaegumi 2017-06-28 08:17:10 +08:00
用 guzzlehttp 库,我真搞不懂为啥还有人要自己实现这些功能。
|
5
q409195961 2017-06-28 09:00:27 +08:00
用 curl 试试
按接口要求,可加上 UserAgent 和请求头数据 ``` $url = "http://localhost/socket/post.php"; $postData = array("username" => "zhangsan","age" => "8"); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 使用 POST 请求 curl_setopt($ch, CURLOPT_POST, 1); // POST 参数 curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); $output = curl_exec($ch); curl_close($ch); // 返回的数据 print_r($output); ``` |
6
kfll 2017-06-28 11:46:56 +08:00
内容格式不大对,建议再看一下 http 规范。
那一段差不多应该是这样 $post = 'POST '.$fh['path'].' HTTP/1.1'."\r\n"; $post .= 'Host: '.$fh['host']."\r\n"; $post .= 'Content-type: application/x-www-form-urlencoded'."\r\n"; $post .= 'Content-length:'.' '.$len."\r\n"; $post .= "Connection: Close\r\n\r\n" ; $post .= $data; -- entity header 跟 entity body 分开;用两个合法换行分开;如果定义了 Content-Length,尽量让 entity body 的大小跟 Content-Length 一样大 |
7
Takahashi 2017-06-28 12:25:59 +08:00
建议 CURL
|