簡體   English   中英

將JSON POST請求發送到PHP中的REST API

[英]Sending a JSON POST request to REST API in PHP

我需要使用JSON對象作為正文進行POST請求。 這兩種方法都給我HTTP 500服務器錯誤。 我的代碼有什么明顯的錯誤嗎? 保持溫柔...我嘗試了幾種方法,包括

$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);

哪個使用HTTPful資源。 我嘗試使用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);

您的json_encode需要一個數組

它應該看起來像這樣

<?php

$checkfor = ([
    'serverId'=>'Server',
    'featureId'=>'Feature',
    'propertyId'=>'Property'
]);

$checkforJson = json_encode($checkfor);
var_dump($checkforJson); // this will now work

https://3v4l.org/RG5Zv

為了更好地理解,請閱讀文檔

更新我也注意到在curl腳本上,您的數組需要再次修復

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

然后不對發布字段進行json編碼,它需要一個數組。

我前段時間有類似的問題。

一個對我有用的解決方案是:

$url = 'http://yourURL.com/api';
$data = array('field1' => 'value', 'field2' => 'value');
$options = array(
        'http' => array(
        'header'  => "Content-type: application/json\r\n",
        'method'  => 'POST',
        'content' => json_encode($data),
    )
);

$context  = stream_context_create($options);
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result );

類似的答案可以在這里找到

你有沒有嘗試過:

$body = array(
  "serverId" => "Server",
  "featureId" => "Feature",
  "propertyId" => "Property",
);

$body = json_encode($body);

也許是您設置陣列的方式

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM