PHP使用curl提交json格式数据

1
2
3
4
5
6
$params = array();
foreach ($_POST as $key => $value) {
$params[$key] = $value;
}

echo request_post($url, $params);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
function request_post($url = '', $params = '', $timeout = 5000)
{
if (empty($url) || empty($params)) {
return '{}';
}

$header = array(
"Accept: application/json",
"Content-Type: application/json",
);

$jsonData = json_encode($params);
$postUrl = $url;
$ch = curl_init();//初始化curl
curl_setopt($ch, CURLOPT_URL, $postUrl);
//curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt ( $curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, false);
$data = curl_exec($ch);//运行curl
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$response = array();

$response['httpCode'] = $httpCode;
$response['data'] = json_decode($data);

return json_encode($response);
}

function request_get($url = '', $params = '', $timeout = 5000)
{
if (empty($url) || empty($params)) {
return '{}';
}

$header = array(
"Accept: application/json",
//"Content-Type: application/json",
);

$linkedData = buildLinkedParams($params);
$getUrl = $url . '?' . $linkedData;

$ch = curl_init();//初始化curl
curl_setopt($ch, CURLOPT_URL, $getUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ( $curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, false);
$data = curl_exec($ch);//运行curl
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$response = array();

$response['httpCode'] = $httpCode;
$response['data'] = json_decode($data);

return json_encode($response);
}

/**
* 拼接参数:key1=value1&key2=value2
* @param $params
* return
*/
function buildLinkedParams($params)
{
$str = "";
while (list ($key, $val) = each ($params)) {
$str .= $key . "=" . $val . "&";
}
//去除最后&符
$str = substr($str, 0, count($str)-2);
//去除转义符
if (get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return $str;
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :