Простой запрос CURL GET
: (Также добавлены json / headers, если требуется, чтобы облегчить вашу жизнь при необходимости)
<?php
$chTest = curl_init();
curl_setopt($chTest, CURLOPT_URL, "http://example.com:8080/?query=Hello+World");
curl_setopt($chTest, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8', 'Accept: application/json'));
curl_setopt($chTest, CURLOPT_HEADER, true);
curl_setopt($chTest, CURLOPT_RETURNTRANSFER, true);
$curl_res_test = curl_exec($chTest);
$json_res_test = explode("\r\n", $curl_res_test);
$codeTest = curl_getinfo($chTest, CURLINFO_HTTP_CODE);
curl_close($chTest);
?>
Пример POST
запрос:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://example.com:8080');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8', 'Accept: application/json'));
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, '{"Hello" : "World", "Foo": "World"}');
// Set timeout to close connection. Just for not waiting long.
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$curl_res = curl_exec($ch);
?>
Charset не является обязательным HTTP-заголовком, как и остальные, важным является Content-Type .
Для примеров, в которых я использовал тип JSON MIME, вы можете использовать все, что захотите, взгляните на ссылку:
http://en.wikipedia.org/wiki/Internet_media_type
Убедитесь, что на вашем php включено расширение php_curl.dll
, а также что порты на целевой службе открыты.
Надеюсь, это поможет.