douhan9467 2011-01-21 16:29
浏览 58
已采纳

使用php调用webservice

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));
  • 写回答

3条回答 默认 最新

  • douruhu4282 2011-01-21 16:52
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Pwm双极模式H桥驱动控制电机
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题