我需要使用 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);
Run Code Online (Sandbox Code Playgroud)
它使用 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);
Run Code Online (Sandbox Code Playgroud)
不久前我遇到了类似的问题。
对我有用的解决方案是:
$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 );
Run Code Online (Sandbox Code Playgroud)
类似的答案可以在这里找到