HttpWebRequest调用API

public void HttpWebRequestPost()
{
            string responseContent = string.Empty;
            var userNameAndPwd = new { userNameOrEmailAddress = "admin", password = "admin"};
            var jsonTest = JsonConvert.SerializeObject(userNameAndPwd);//序列化传输的对象
            byte[] byteArray = Encoding.UTF8.GetBytes(jsonTest);
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(abpTokenUrl);//需要请求的网址
            request.Method = "POST";
            request.ContentType = "application/json";//头部(文件一定要写)
            request.ContentLength = byteArray.Length;
            using (Stream reqStream = request.GetRequestStream())
            {
                reqStream.Write(byteArray, 0, byteArray.Length);

            }
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())  //获取request的返回结果
            {

                using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default))  //读取返回流
                {
                    responseContent = sr.ReadToEnd().ToString();
                    var jsonResult = JsonConvert.DeserializeObject(responseContent);
                    
                }
            }
}

 

posted on 2020-03-16 16:11  三千世界a  阅读(202)  评论(0编辑  收藏  举报

导航