How to make a PUT HTTP REQUEST to ( http://sample.com:8888/folder ) with a Random-Header and REQUEST-BODY with JSON String {"key": "la09823", "content": "jfkdls"} HTTP status code 200 OK would be nice. Sorry for my first socket confusing php code :D<3. thx
<?php
$json = "\{\"key\": \"la09823\", \"content\": \"jfkdls\"}";
$hostname="http://sample.com/folder");
$port = 8888;
$timeout = 50;
$socket = socket_create(AF_INET, SOCK_STREAM, tcp);
socket_connect($socket, $hostname, $port);
$text = "PUT /folder/json.txt" HTTP/1.1\n";
$text .= "Host: WhoIAm.com\n";
$text .= "Content-Type: application/json\n";
$text .= "Content-length: " . strlen($json) . "\n";
$finish = $text + $json;
socket_write($socket, $finish, 0);
socket_close($socket);
?>
Don't use raw sockets to make HTTP requests. There are much better libraries for that, like cURL:
<?php
$data = [
"key" => "la09823",
"content" => "jfkdls",
];
$req = curl_init();
curl_setopt_array($req, [
CURLOPT_URL => "https://httpbin.org/put",
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_HTTPHEADER => [ "Content-Type" => "application/json" ],
CURLOPT_RETURNTRANSFER => true,
]);
$response = curl_exec($req);
print_r($response);
(I've used httpbin for testing this code. Obviously, you'll want to use a different URL here.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.