使用PHP curl调用webservice

I'm currently trying to call a POST web service with the PHP curl. I tried this, but without success (I receive "false", the objective is to receive a string from my web-service):

function devis( $data){
    $typeDevis = $data['typeDevis'];
    $compo = $data['compo'];
    $offre = $data['offre'];

    $url = "https://someadress:port/apiname/api/Devis";
    try{
        $fields = array(
            'typeDevis' => $typeDevis,
            'compo' => $compo,
            'offre' => $offre,
        );

        $fields_string = http_build_query($fields);

        $ch = curl_init();

        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_POST, count($fields));
        curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

        $result = curl_exec($ch);

        curl_close($ch);
        return $result;
    }catch (Exception $e) {
        return $e;
    }
}

The link that must be called in POST is for example:

https://someadress:port/apiname/api/Devis?typeDevis=VALUE1&compo=VALUE2&offre=VALUE3

Does anyone have any ideas?

douyao1856
douyao1856 您发布的URL是在查询字符串中传递数据,建议它应该是GET,而不是POST?或者,如果它需要是POST,那么您应该将数据添加到$url-variable,以便它看起来就像您发布的示例链接。
大约一年之前 回复

1个回答

You need to modify your function as following:

function devis($data){
    $typeDevis = $data['typeDevis'];
    $compo = $data['compo'];
    $offre = $data['offre'];

    $url = "https://someadress:port/apiname/api/Devis";
    try{
        $fields = array(
            'typeDevis' => $typeDevis,
            'compo' => $compo,
            'offre' => $offre,
        );

        // You don't need to use this
        //$fields_string = http_build_query($fields);

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        $result = curl_exec($ch);

        curl_close($ch);
        return $result;
    }catch (Exception $e) {
        return $e;
    }
}

Try to use proper curl syntax and be specific what you want to implement.
Also it would be better if you'll provide a proper header to your API request.

dongzi1209
dongzi1209 谢谢您的回答! 实际上,该方法必须在POST中(出于安全原因,已经强制执行)。 当使用POST方法调用REST链接时,原理与SoapUI(对于那些知道的人)相同。 我来看看Header。
大约一年之前 回复
douningzhi1991
douningzhi1991 恕我直言,我们应该等到OP澄清了数据应该如何传递以及它是否真的应该是POST。
大约一年之前 回复
doudui2229
doudui2229 是啊,你说得对。 也许我错误地得到了这个网址。 顺便说一句,这在我的回答中并不重要。
大约一年之前 回复
dongtanlin0765
dongtanlin0765 “你在URL本身中传递查询参数。在你的上下文中哪些不正确” - 当我读到这个问题时,反过来说。 他们的代码在他们发布的示例网址中没有传递URL中的数据。
大约一年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐