php发送post请求

无人久伴 提交于 2019-12-28 12:12:04

Http中传输对象,最好的表现形式莫过于 JSON 字符串了,但是作为参数的接收方,又是需要被告知传过来的是JSON!

function http_post_json($url, $jsonStr)
{
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array(
      'Content-Type: application/json; charset=utf-8',
      'Content-Length: ' . strlen($jsonStr)
    )
  );
  $response = curl_exec($ch);
  $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  return array($httpCode, $response);
}
$url = "http://blog.snsgou.com";
$jsonStr = json_encode(array('a' => 1, 'b' => 2));
list($returnCode, $returnContent) = http_post_json($url, $jsonStr);

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!