近期遇到一个很诡异的情况,对接某个https接口,对方的接口在使用postman模拟的时候一切正常,但在上代码curl提交的时候直接502了。
折腾了很久也没有解决,后面直接用shell命令curl发现也无法提交,返回 code:500 的错误。
网上找了很久,有说要重装curl的,有说要重新编译php的,不一而足。
这些方法都太过复杂,而且是生产环境,不可能任我胡来。后面想起是不是可以换种请求方式呢,于是就有了下面的方法
JSON方式模拟人工提交:
function send_post($url, $params) { $data_string = json_encode($params); $options = array( 'http' => array( 'method' => 'POST', 'header' => array( 'User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:33.0) Gecko/20100101 Firefox/33.0', 'Content-Type: application/json', //'Authorization: Basic'.base64_encode($this->appId.':'.$this->key.''), //添加头,在name和pass处填写对应账号密码 ), 'content' => $data_string, 'timeout' => 15 * 60 // 超时时间(单位:s) ) ); $context = stream_context_create($options); $result = file_get_contents($url, false, $context); return $result; }
Form表单方式提交:
function send_post($url, $post_data) { $postdata = http_build_query($post_data); $options = array( 'http' => array( 'method' => 'POST', 'header' => 'Content-type:application/x-www-form-urlencoded', 'content' => $postdata, 'timeout' => 15 * 60 // 超时时间(单位:s) ) ); $context = stream_context_create($options); $result = file_get_contents($url, false, $context); return $result; }
使用方法:
//使用方法 $post_data = array( 'username' => 'xx', 'password' => 'xx'); send_post('http://www.baidu.com', $post_data);