【问题标题】:Making a call to my webservice via curl doesn't work通过 curl 调用我的网络服务不起作用
【发布时间】:2014-01-09 16:41:46
【问题描述】:

我有一个简单的函数来通过POST 测试我的网络服务,如下所示:

  function service(){
    $service_url = 'http://example.com/example_endpoint/user';
    $curl = curl_init($service_url);
    $header = array(
      'Content-Type: application/x-www-form-urlencoded'
    );
    $curl_post_data = array(
      "name" => "name_test",
      "mail" => "name_test@example.com",
      "pass" => "123",
    );
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    $curl_response = curl_exec($curl);
    curl_close($curl);

    $xml = new SimpleXMLElement($curl_response);
  }

网络服务正在指定数组上的参数,并且 Content-Type 应该是 application/x-www-form-urlencoded 但是当我在浏览器中运行该函数并检查“检查元素”上的“网络”选项卡时,有一个调用通过GET 到我的网络服务,尽管我将选项设置为POST 并且 Content-Type 保持在text/html

该网络服务允许使用数组$curl_post_data中的参数创建用户

我使用Mozilla上的插件“海报”来调用我的网络服务并且它是成功的,但是当我调用上面的函数时它不起作用¿我怎样才能实现这个函数来进行正确的调用?

【问题讨论】:

    标签: web-services post curl get


    【解决方案1】:

    在浏览器的网络选项卡中,您不会看到 POST,因为 curl 正在发布此内容。网络选项卡显示来自客户端(浏览器)的活动。服务器通过 CURL 发布您的数据。

    添加此代码以正确地对数据进行 url 编码

    $curl_post_data_string = '';
    //url-ify the data for the POST
    foreach($curl_post_data as $key => $value) {
        $curl_post_data_string .= $key.'='.$value.'&';
    }
    rtrim($curl_post_data_string, '&');
    

    然后改变这一行

    curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
    

    请记住,在 CURL 中点击 URL 后,您需要打印 $curl_response 后得到什么

    echo $curl_response;
    

    这是使用 CURL 发布数据的正确示例

    http://davidwalsh.name/curl-post

    【讨论】:

    • 这个调用是为了创建一个新用户,抱歉我没有提到。这不是登录的调用
    • 谢谢,我不知道 POST 没有显示在 NETWORK 选项卡上。
    • 当从客户端发布某些内容时,POST 在网络选项卡上可见。使用您从服务器端发布的 curl 。当从服务器端发出请求时,网络选项卡不显示。
    • 使用 $curl_post_data_string = http_build_query($curl_post_data); 代替 foreach 循环;
    猜你喜欢
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 2015-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多