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条)

报告相同问题?