php 发送post请求

更新于 2022-05-04 00:32 146
专栏: PHP 标签: web php

  1. function request_post($url, $data) {
  2. $str = json_encode($data); //如果传的不是json字符串的话需要转一下
  3. $context = array(
  4. 'http' =>
  5. array(
  6. 'method' => 'POST',
  7. 'header' => 'Content-type:application/json;charset=utf-8' . "\r\n" .
  8. // "Authorization:Basic".base64_encode($con['userid'].":".$con['password'])."\r\n".
  9. 'Content-length' . strlen($str),
  10. 'content' => $str
  11. )
  12. );
  13. $contextid = stream_context_create($context);
  14. $scok = fopen($url, 'r', false, $contextid);
  15. if ($scok) {
  16. $result = '';
  17. while (!feof($scok)) {
  18. $result .= fgets($scok, 4096);
  19. }
  20. fclose($scok);
  21. return $result;
  22. } else {
  23. return $str;
  24. }
  25. }

调用

  1. $new_platform_data=[];
  2. $new_platform_data['imei'] = $device_id;
  3. $new_platform_data['sensor_status'] = $sensor_status;
  4. $new_platform_data['battery_value'] = $battery_value;
  5. $new_platform_data['temperature'] = $temperature;
  6. $new_platform_data['pressure'] = $pressure;
  7. $new_platform_data['wake_up'] = "{$wakehour}:{$wakeminute}:{$wakesecond}";
  8. try {
  9. request_post('http://127.0.0.1:1991/index/getData', $new_platform_data);
  10. } catch (\Exception $e) {
  11. echo_content("旧设备推送数据到新平台出错");
  12. }

BLOG

搜索文章