【问题标题】:Getting a reponse from a web api in JSON format从 Web api 获取 JSON 格式的响应
【发布时间】:2019-11-26 01:35:14
【问题描述】:

我是web serviceAPI 的新手,并尝试使用post 方法从URL 获取响应并将参数传递给它。我正在开发一个 C# winform 应用程序,它向这个api 发送请求,并且必须以 JSON 格式返回输出。下面是我的代码,所以我只得到一个 OK 响应而不是实际的 JSON 数据。

private void button1_Click(object sender, EventArgs e)
        {
            string postData = "station=sub";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);



            Uri target = new Uri("http://apijsondata/tz_api/");
            WebRequest myReq = WebRequest.Create(target);

            myReq.Method = "POST";
            myReq.ContentType = "application/x-www-form-urlencoded";
            myReq.ContentLength = byteArray.Length;

            using (var dataStream = myReq.GetRequestStream())
            {
                dataStream.Write(byteArray, 0, byteArray.Length);
            }

            using (var response = (HttpWebResponse)myReq.GetResponse())
            {
                //Do what you need to do with the response.
                MessageBox.Show(response.ToString());
            }


        }

【问题讨论】:

    标签: c# json rest api


    【解决方案1】:

    您应该将StreamReaderHttpWebResponse.GetResponseStream() 一起使用

    例如,

     var reader = new StreamReader(response.GetResponseStream());
     var json = reader.ReadToEnd();
    

    【讨论】:

      猜你喜欢
      • 2018-11-03
      • 1970-01-01
      • 1970-01-01
      • 2018-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-20
      • 1970-01-01
      相关资源
      最近更新 更多