使用httpwebrequest发送http请求

 HttpWebRequest request = WebRequest.Create("url") as HttpWebRequest;
            request.Timeout = 8 * 60 * 1000;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";//数据放在body中,以键值对形式
            request.KeepAlive = true;
            request.Headers.Add("Authorization", Authorization);//api 的验证 信息
            string ss = System.Web.HttpUtility.UrlEncode("key") + "=" + System.Web.HttpUtility.UrlEncode(value);//参数使用urlencode编码,
//空格全部用+代替
byte[] postData = encoding.GetBytes(ss); request.ContentLength = postData.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(postData, 0, postData.Length); requestStream.Close(); var response = (HttpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); StreamReader reader = new StreamReader(responseStream, encoding); string result = reader.ReadToEnd(); reader.Close(); responseStream.Close();

2 拿到api返回的json格式之后使用newtonsoft来反序列化

 private static T DeserializeObject<T>(string equityJson)
        {
//将返回的json反序列化成objec object _object = JsonConvert.DeserializeObject(equityJson);
//转换成jobject Newtonsoft.Json.Linq.JObject jObject = _object as Newtonsoft.Json.Linq.JObject;
//根据键值对的形式拿到对应的value string dataJson = jObject["data"].ToString(); object dataObj = JsonConvert.DeserializeObject(dataJson); JObject jdataObj = dataObj as JObject; string capabilityResults = jdataObj["capabilityResults"].ToString(); object capabilityResultsObj = JsonConvert.DeserializeObject(capabilityResults); JObject jcapabilityResultsObj = capabilityResultsObj as JObject; string equity_name_matching = jcapabilityResultsObj["equity_name_matching"].ToString(); T equityMatchReturn = JsonConvert.DeserializeObject<T>(equity_name_matching); return equityMatchReturn; }

  

posted @ 2019-08-23 11:38  白羽轻飘  阅读(2119)  评论(0编辑  收藏  举报