donglun2024 2018-10-25 11:18
浏览 323
已采纳

在PHP中向REST API发送JSON POST请求

I need to make a POST request using a JSON object as the body. Both of these methods are giving me HTTP 500 server errors. Is there anything glaringly wrong with my code? Be gentle... I've tried several methods including

$checkfor = ("'serverId':'Server','featureId':'Feature','propertyId':'Property'");
    $checkforJson = json_encode($checkfor);
    $uri = "http://localhost:8080/v1/properties";
    $response = \Httpful\Request::post($uri)
    ->method(Request::post)
    ->withoutStrictSsl()
    ->expectsJson()
    ->body($checkforJson)
    ->send();
    pre($response);

Which uses the HTTPful resource. And I have tried using cURL

$service_url = "http://localhost:8080/v1/properties";

   // Initialize the cURL
   $ch = curl_init($service_url);

   // Set service authentication

   // Composing the HTTP headers     
   $body = array();
   $body[] = '"serverId" : "Server"';
   $body[] = '"featureId" : "Feature"';
   $body[] = '"propertyId" : "Property"';
   $body = json_encode($body);

   $headers = array();
   $headers[] = 'Accept: application/xml';
   $headers[] = 'Content-Type: application/xml; charset=UTF-8';

   // Set the cURL options
   curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
   curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
   curl_setopt($ch, CURLOPT_POST, TRUE);
   curl_setopt($ch, CURLOPT_VERBOSE, 1);
   curl_setopt($ch, CURLOPT_HEADER, TRUE);
   curl_setopt($ch, CURLINFO_HEADER_OUT, true);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

   curl_setopt($ch, CURLOPT_TIMEOUT, 15);

   // Execute the cURL
   $data = curl_exec($ch);

   // Print the result
   pre($data);
  • 写回答

3条回答 默认 最新

  • dtufl26404 2018-10-25 11:25
    关注

    Your json_encode requires an array.

    It should look like this

    <?php
    
    $checkfor = ([
        'serverId'=>'Server',
        'featureId'=>'Feature',
        'propertyId'=>'Property'
    ]);
    
    $checkforJson = json_encode($checkfor);
    var_dump($checkforJson); // this will now work
    

    https://3v4l.org/RG5Zv

    For better understanding read doc

    UPDATE I also notice on the curl script, your array needs fixed again

     $body['serverId'] = 'Server';
    

    and dont json encode the post fields afterwards, it takes an array.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵