php post application/json
时间: 2023-07-29 17:09:38 浏览: 51
在 PHP 中进行 POST 请求并发送 JSON 数据,可以使用 `curl` 库。
```php
$url = "http://example.com/api";
$data = array('username' => 'john', 'password' => 'doe');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen(json_encode($data)))
);
$response = curl_exec($ch);
curl_close($ch);
// 处理响应
```
这里需要注意的是,需要在请求头中设置 `Content-Type` 为 `application/json`,并且发送的数据需要进行 JSON 编码。
相关问题
php post 请求 Content-Type: application/json;charset=utf8
如果你要使用 PHP 发送 POST 请求,并且请求体的 Content-Type 是 application/json;charset=utf8,你可以使用以下代码:
```php
$url = 'http://example.com/api';
$data = array('name' => 'John', 'age' => 30);
$options = array(
'http' => array(
'header' => "Content-type: application/json;charset=utf8\r\n",
'method' => 'POST',
'content' => json_encode($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$response = json_decode($result);
```
这个代码会使用 `file_get_contents` 函数发送一个 POST 请求到指定的 URL,并且请求体是一个 JSON 格式的字符串。在请求头中设置了 Content-Type 为 application/json;charset=utf8。最后,使用 `json_decode` 函数将返回的 JSON 字符串解析为 PHP 对象或数组。
php 获取curl请求参数 如下列:POST /rest/httpsessions/callnotify/v2.0 HTTP/1.1 content-type: application/json;charset=UTF-8
你可以使用 `$_POST` 来获取 POST 请求中的参数,可以使用 `file_get_contents("php://input")` 来获取请求体中的内容,然后再使用 `json_decode()` 函数将 JSON 字符串转换成 PHP 对象或数组。以下是示例代码:
```php
// 获取 POST 请求中的参数
$param1 = $_POST['param1'];
$param2 = $_POST['param2'];
// 获取请求体中的内容
$request_body = file_get_contents("php://input");
// 将 JSON 字符串转换成 PHP 对象或数组
$request_data = json_decode($request_body);
```
注意,如果请求头中包含了 `content-type: application/json`,则请求体中的内容应该是一个 JSON 格式的字符串。如果请求头中包含了其他的 Content-Type,那么请求体的格式也会有所不同。需要根据实际情况来进行处理。