Winform中调用WebApi并解析返回数据

 private async void button1_Click(object sender, EventArgs e)
        {
          
           DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(HardwareStatusBase));
            MemoryStream ms = new MemoryStream();
            //将资料写入MemoryStream
            serializer.WriteObject(ms, new HardwareStatusBase()
            {
                IP = "192.168.0.13",
                port = "8081",
                Devicecode = "BB7584",
                DeviceName = "报警器",
                DeviceStatuss = 1,
                message = "设备打开",
                operation = 1
            });
            //一定要在这设定Position
            ms.Position = 0;
            HttpContent content = new StreamContent(ms);//将MemoryStream转成HttpContent
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            HttpClient client = new HttpClient();
            //由HttpClient发出Put Method
            HttpResponseMessage response = await client.PostAsync("http://192.168.0.11:8011/HardwareStatus/HardwareStatus", content);
            string result = await response.Content.ReadAsStringAsync();//将调用API返回数据转换为字符串
            if (response.IsSuccessStatusCode)
                MessageBox.Show(result);
        }

posted @ 2019-05-05 14:35  执念、旧时光  阅读(924)  评论(0编辑  收藏  举报