Home > Backend Development > PHP Tutorial > How to submit json data with curl

How to submit json data with curl

angryTom
Release: 2023-04-08 07:28:01
forward
3613 people have browsed it

How to submit json data with curl

最近在开发一个接口对接的网站,对方的系统用的java开发的,我这里开发用php开发,提交数据的时候用的json格式

为此在网上找了一下curl提交json数据的代码

在此记录一下 推荐:《PHP教程》 

/**
 * 远程获取数据,POST json数据
 * 注意:
 * 1.使用Crul需要修改服务器中php.ini文件的设置,找到php_curl.dll去掉前面的";"就行了
 * 2.文件夹中cacert.pem是SSL证书请保证其路径有效,目前默认路径是:getcwd().'\\cacert.pem'
 * @param $url 指定URL完整路径地址
 * @param $cacert_url 指定当前工作目录绝对路径
 * @param $para 请求的数据 数组
 * @param $input_charset 编码格式。默认值:空值
 * return 远程输出的数据
 */
function getHttpResponsePOSTjson($url, $para, $cacert_url='', $input_charset = '') {
    if (trim($input_charset) != '') {
        $url = $url."_input_charset=".$input_charset;
    }
    $data_string=json_encode($para,JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE);
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);//$data JSON类型字符串
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);//SSL证书认证
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//严格认证
    curl_setopt($curl, CURLOPT_CAINFO,$cacert_url);//证书地址
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($data_string)));
    $result = curl_exec($curl);
    curl_close($curl);
    return $result;
}
Copy after login

之后跟java打交道还是挺多的,在此分享一下。

更多PHP相关知识,请访问PHP中文网

The above is the detailed content of How to submit json data with curl. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:小松博客
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template