I am new to PHP and wanted to write a snippet of code which would call a Webservice. I have the java equivalent code for it that works correctly.
HttpClient client=new HttpClient();
GetMethod method=new GetMethod(URL);
method.addRequestHeader("test1","test1");
String statusCode=client.executeMethod();
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
}
// Read the response body.
byte[] responseBody = method.getResponseBody();
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
System.out.println(new String(responseBody));
Your should use some webservice dedicated methods, it would be easier. For example if your webservice is a SOAP one : http://php.net/manual/fr/book.soap.php , or an XML-RPC : http://www.php.net/manual/en/book.xmlrpc.php
Look at httprequest-send in php, that should get you started in terms of building the right request.
There are a bunch of different ways to do it.
If you're just trying to send a simple GET request, file_get_contents
will work just fine. (Note: you can also do POST requests with file_get_contents
in conjunction with stream_context_create
, but there are other ways I find nicer)
Example:
$response = file_get_contents("http://www.example.com/webservice?foo=bar&baz=1");
Another method is to use cURL
. This may not be available on all systems (but should be on most). Here's an example of a POST request using curl:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/webservice');
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('foo'=>'bar','baz'=>1)));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$result = curl_exec($ch);
Alternatively, another way is to use the PEAR package HTTP_Request2 . This will work on all systems and can be a nice way to do it. For more information and examples, see the manual page .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.