php - curl post请求java服务端提供的接口
巴扎黑
巴扎黑 2017-04-10 17:39:05
0
2
338

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
    ];
}
巴扎黑
巴扎黑

reply all(2)
Peter_Zhu

一般是header中的标注的json格式有问题。可以着重关注下这块。

Peter_Zhu

查看下返回的数据是否含有BOM

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!