下面的实例为发送短信请求至某一api,返回流数据,为json类型
//最终短信返回结果
static string Res = "";
//为抛出异常,返回的json字符串对应状态码的结果
static string resuleJson = "";
//状态码 代码最后有对应的
static string stateNum = "";
//要请求的url地址
string url = "http://*******";
//http发送请求及响应
HttpWebRequest req = null;
HttpWebResponse response = null;
Stream writer = null;
XmlDocument xml = new XmlDocument();
req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";//发送请求的方法
req.ContentType = "application/json";
//要发送的请求体
string content = "{\"account\":\"admin\",\"password\":\"111111\",\"businessType\":\"6666666\"}";
Stream myRequestStream = req.GetRequestStream();
StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("utf-8"));
myStreamWriter.Write(content);
myStreamWriter.Close();
try
{
response = (HttpWebResponse)req.GetResponse(); //获得响应
}
catch (WebException ex)
{
Log.Info(ex.Message);
Res = "调用req.GetResponse时:" + ex.Message;
return;
}
//这种方式读取到的是一个返回的结果字符串
try
{
Stream stream = response.GetResponseStream(); //获取响应流
StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("UTF-8"));
resuleJson = reader.ReadToEnd();
reader.Close();
stream.Close();
}
catch (Exception ex)
{
Log.Info( ex.Message);
Res = (ex.Message);
return;
}
//此处代码为将string类型的resuleJson(json格式的字符串)
//进行获取并对值进行判断
//使用时项目中引用json.NET
//代码中引用using Newtonsoft.Json.Linq;
//才可以使用JObject
JObject j = JObject.Parse(resuleJson);
stateNum = j["code"].ToString();
if (stateNum == "0")
{
Res = "success";
return;
}
版权声明:本文为weixin_34024244原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。