php - curl post请求java服务端提供的接口

 陈民翔芷昌柏淑 发布于 2022-11-17 19:47

post请求此接口是通的,但是PHP程序中请求就报500 ,下面贴代码 参数是他们需要的参数,格式也是按照定下来的标准。。很诡异。。各位大神遇到过吗

$this->sendRequest('POST', $url, json_encode($params), ['Content-Type: application/json']);

/**
 * 发送HTTP请求,获取响应结果
 *
 * @param string $method 请求方法
 * @param string $url 请求地址
 * @param array $params 请求体参数
 * @param array $headers 请求头
 * @param bool|string $https 是否启用证书认证,可传入证书路径
 *
 * @return array
 */
protected function sendRequest($method, $url, $params = [], $headers = [], $https = false)
{
    // 标准化请求方法
    $method = strtoupper($method);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_URL, $url);

    // 写入Headers
    if ($headers) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }

    // 控制请求参数
    if ($method != 'GET') {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);

        if ($method != 'POST') {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        }
    }

    // Https证书
    if (stripos($url, 'https') === 0) {
        if ($https && is_string($https)) { // 传入证书路径
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
            curl_setopt($ch, CURLOPT_CAINFO , $https);
        } else {
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $https ? 2 : 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $https ? 1 : 0);
        }
    }

    curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $content = curl_multi_getcontent($ch);
    curl_close($ch);

    return [
        'status' => $status,
        'content' => $content
    ];
}
2 个回答
  • 查看下返回的数据是否含有BOM

    2022-11-17 20:49 回答
  • 一般是header中的标注的json格式有问题。可以着重关注下这块。

    2022-11-17 20:49 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有