如何从webservice中保存变量中的响应

时间:2016-03-06 21:06:28

标签: c# winforms web-services webservice-client

我是网络服务的新手,我有飞行状态的试用版,如何在C#中获得响应?

我有以下网络服务

https://api.flightstats.com/flex/airlines/soap/v1/airlinesService?wsdl
https://api.flightstats.com/flex/schedules/soap/v1/scheduledFlightsService?wsdl

我想调用它的方法和响应保存在我的变量中,但它显示错误;(我已经通过服务引用添加了这个服务并调用它的方法。

这是我的代码 - 请帮助

private void button1_Click(object sender, EventArgs e)
{
    ServiceReference2.flightServiceClient obje = new Windowsflightstate.ServiceReference2.flightServiceClient();

    // How to get response 
    string[] resultdata = obje.flightStatus_arr("b2113423", "65fa387418310aec95a688737f8e0b13", "", "EK4158", 2016, 03, 07, "", "", "", "");

    flightscheduleswebservice.scheduledFlightServiceClient client = new Windowsflightstate.flightscheduleswebservice.scheduledFlightServiceClient();
    client.byFlight_Arriving("b2113423", "65fa387418310aec95a688737f8e0b13",null, "EK4158", 2016, 03, 07, null, null);

    // it is showing error how to get response
    string[] resultdata2 =  client.byFlight_Arriving("b2113423", "65fa387418310aec95a688737f8e0b13", null, "EK4158", 2016, 03, 07, null, null);
}

请看这张图片:

enter image description here

1 个答案:

答案 0 :(得分:2)

只需使用此代码 - 将Web服务调用中的响应分配给Web服务方法返回的数据类型(类):

private void button1_Click(object sender, EventArgs e)
{
    ServiceReference2.flightServiceClient obje = new Windowsflightstate.ServiceReference2.flightServiceClient();

    // How to get response 
    flightscheduleswebservice.responseByFlight resultdata = obje.flightStatus_arr("b2113423", "65fa387418310aec95a688737f8e0b13", "", "EK4158", 2016, 03, 07, "", "", "", "");

    // show errors if any
    Console.WriteLine("HTTP status code: {0}", resultdata.error.httpStatusCode);
    Console.WriteLine("Error code: {0}", resultdata.error.errorCode);
    Console.WriteLine("Error message: {0}", resultdata.error.errorMessage);

    // display info, if any
    if (resultdata.scheduledFlights != null && resultdata.scheduledFlights.Length > 0)
    {
        Console.WriteLine("Number of flights returned: {0}", resultdata.scheduledFlights.Length);
        Console.WriteLine("Flight #1 - carrier name: {0}", resultdata.scheduledFlights[0].carrier.name);
        Console.WriteLine("Flight #1 - departure airport name: {0}", resultdata.scheduledFlights[0].departureAirport.name);
        Console.WriteLine("Flight #1 - arrival airport name: {0}", resultdata.scheduledFlights[0].arrivalAirport.name);
    }
}

从错误中显而易见,Web服务调用返回一个名为 flightscheduleswebservice.responseByFlight 的类的实例 - 而不是您正在尝试的字符串数组将其分配给。

使用C#中的内置机制来使用Web服务的关键在于您获得了一个很好的响应对象 - 而不仅仅是一堆XML字符串。您不需要自己解析XML响应 - ServiceReference2.flightServiceClient类处理所有这些 - 您可以获得一个可以使用的漂亮,正常的.NET 对象