我的内容类型正在我的curl请求上被覆盖

时间:2013-04-17 16:27:08

标签: php curl

编辑:事实证明数据发送得很好,但在PHP中查看正文无法正常工作。有关详细信息,请参阅我的回答。

我正在尝试将json数据发布到服务器。我只需要将内容类型设置为json,并将主体设置为具有json格式的字符串。 我的问题是内容类型保留为text / html,无论我尝试什么,我都无法改变内容类型。我读了很多堆栈溢出答案,他们看起来都应该工作,但他们没有。我的代码如下。

  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
  curl_setopt($ch, CURLOPT_HEADER, 1);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));      
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
  curl_exec($ch);

在接收端,我只是打印getallheaders和get_file_contents('file:// phpinput')。

为什么我的内容类型不正确?

如果有帮助,这是一个示例输出:

string 'HTTP/1.1 200 OK
Date: Wed, 17 Apr 2013 16:24:56 GMT
Server: Apache/2.2.22 (Unix) mod_ssl/2.2.22 OpenSSL/0.9.8r DAV/2 PHP/5.4.4
X-Powered-By: PHP/5.4.4
Content-Length: 71
Content-Type: text/html

Array{"level1a":{"level2":{"a":2,"b":3}},"level2b":["111","333","999"]}' (length=273)

2 个答案:

答案 0 :(得分:1)

您需要创建两个php文件,一个客户端(client.php)和一个服务器(server.php)。

服务器读取json请求并发回(json)响应。 您的客户端将json发送到te服务器并读取响应。

您需要在网络服务器http://localhost/server.php上使用server.php。 您可以从相同或其他服务器http://localhost/client.php运行客户端。 您还可以从命令行php -f client.php

运行客户端

server.php:

<?
// read json input
$input = json_decode(file_get_contents('php://input'));
$response = array('text'=>'Your name is: '.$input->{'name'});
header("Content-type: application/json");
// send response
echo json_encode($response);
exit;

client.php:

<?
$data = array('name'=>'Jason'); // input
$ch = curl_init('http://localhost/server.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));      
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$result = curl_exec($ch);
curl_close($ch);
list($headers, $content) = explode("\r\n\r\n", $result, 2);
$php = json_decode($content);
echo 'Response: ' . $php->text;
// if you want to know
var_dump($headers);
exit;

答案 1 :(得分:0)

事实证明没有错。 我不确定“数组”部分来自哪里,但我发布的API收到的数据很好。 我认为如果有人发布了一种方法来查看卷曲请求发送的确切内容会更好,这样人们可以比我更容易排除故障。