通过curl PHP或类似的东西访问Web服务

时间:2018-02-01 10:32:17

标签: php web-services curl php-curl

我有这种类型的API代码,如何在php中发送访问此Web服务的请求?我可以用卷发吗?请帮帮我

沙盒网址: http://api.lankagate.gov.lk:8280/GetOnGoingVehicleNoDMT/1.0 方法POST

参数名称 - vehicleCategory 选项 - 1,4

成功回应代码:200

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <soap:Body>
 <GetOnGoingVehicleNoResponse
xmlns="http://schemas.conversesolutions.com/xsd/dmticta/v1">
 <return>
 <ResponseMessage xsi:nil="true" />
 <ErrorCode xsi:nil="true" />
 <OngoingVehicleNo>CAW-2186</OngoingVehicleNo>
 </return>
 </GetOnGoingVehicleNoResponse>
 </soap:Body>
</soap:Envelope>

Sample

Call URL : http://api.lankagate.gov.lk:8280/Transliteration/1.0/
Message body :
<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:v1="http://schemas.conversesolutions.com/xsd/dmticta/v1">
 <soapenv:Header/>
 <soapenv:Body>
 <v1:GetOnGoingVehicleNo>
 <v1:vehicleCategory>1</v1:vehicleCategory>
 </v1:GetOnGoingVehicleNo>
 </soapenv:Body>
</soapenv:Envelope>

备注将请求标头设置为 授权:承载访问令牌

我试过了,这是我的代码

function get_exam_mode_of_study() {
        $xml_data = '<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:v1="http://schemas.conversesolutions.com/xsd/dmticta/v1">
 <soapenv:Header/>
 <soapenv:Body>
 <v1:GetOnGoingVehicleNo>
 <v1:vehicleCategory>1</v1:vehicleCategory>
 </v1:GetOnGoingVehicleNo>
 </soapenv:Body>
</soapenv:Envelope>';
        $URL = "http://api.lankagate.gov.lk:8280/GetOnGoingVehicleNoDMT/1.0";
        $ch = curl_init($URL);
//        curl_setopt($ch, CURLOPT_MUTE, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml_data");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        print_r($output);
        exit;
        curl_close($ch);
//        }
    }

它会出现以下错误

<ams:fault xmlns:ams="http://wso2.org/apimanager/security"><ams:code>900902</ams:code><ams:message>Missing Credentials</ams:message><ams:description>Required OAuth credentials not provided. Make sure your API invocation call has a header: "Authorization: Bearer ACCESS_TOKEN"</ams:description></ams:fault>

1 个答案:

答案 0 :(得分:0)

您需要添加授权标题

curl_setopt()的CURLOPT_HTTPHEADER采用一个数组,每个头都作为一个元素。

您可以在$ header array下面使用。

$header = array();
$header[] = 'Content-length: 0';
$header[] = 'Content-type: application/json';
$header[] = 'Authorization: Bearer OAuthAccess_TokenThatIReceived';

curl_setopt($ch, CURLOPT_HTTPHEADER,$header);