我已經提供了一個如何連接到某個web服務器的例子。使用post發送數據到webservice
這是一個簡單的形式,它有兩個輸入:
它返回一個單詞和JSON都提交表單後真。
這是代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Webservice JSON</title>
</head>
<body>
<form action="http://foowebservice.com/post.wd" method="post">
<p>
<label for="from">token: </label>
<input type="text" id="token" name="token"><br>
<label for="json">json: </label>
<input type="text" id="json" name="json"><br>
<input type="submit" value="send">
<input type="reset">
</p>
</form>
</body>
</html>
爲了使其充滿活力,我想用PHP來複制它。
$url = "http://foowebservice.com/post.wd";
$data = array(
'token' => 'fooToken',
'json' => '{"foo":"test"}',
);
$content = json_encode($data);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
$response = json_decode($json_response, true);
但我一定是做錯了什麼,因爲$迴應給它一個錯誤的值。
我不介意以任何其他方式做這個,而不是使用Curl。
有什麼建議嗎?
UPDATE
正如在第一個答案的建議,我已經嘗試設置$數據數組中這樣說:
$data = array(
'token' => 'fooToken',
'json' => array('foo'=>'test'),
);
然而,反應也是假的。
我已經試過Postman REST - Client plugin Chrome瀏覽器,並使用開發工具/網絡,在報頭中的網址是:
Request URL:http://foowebservice.com/post.wd?token=fooToken&json={%22foo%22:%22test%22}
我以爲是應該使用curl發送相同的URL。
你就在你的最後一次更新,這就是我在我的答案:) – 2013-04-05 13:05:39
在這種情況下寫的,你應該檢查你的web服務。我測試它在我的apache實例上,它工作。我將工作測試完整代碼附加到我的回答中 – 2013-04-05 13:16:09