1.获取token接口
1 private string gettoken() 2 { 3 // 测试环境登陆用户 4 //string username = "as"; 5 //string password = "as"; 6 7 string Token = string.Empty; 8 try 9 { 10 if (string.IsNullOrEmpty(username) && username == null && string.IsNullOrEmpty(password) && password == null) 11 throw new Exception("调用系统接口:获取token失败 用户名或密码不能发为空!"); 12 var strParm = JsonConvert.SerializeObject(new 13 { 14 username = username, 15 password = password 16 }); 17 //string url = "http接口地址"; // 测试系统地址 18 19 Encoding encode = System.Text.Encoding.Default; 20 Byte[] arrB = encode.GetBytes(strParm); 21 HttpWebRequest Request = (HttpWebRequest)HttpWebRequest.Create(url); 22 Request.Method = "POST"; 23 Request.ContentType = "application/json"; // application/x-www-form-urlencoded 24 25 Request.ContentLength = arrB.Length; 26 //实例化写入请求的参数 27 using (Stream outStream = Request.GetRequestStream()) 28 { 29 outStream.Write(arrB, 0, arrB.Length); 30 outStream.Close(); 31 } 32 33 //接受http响应 34 HttpWebResponse myResponse = Request.GetResponse() as HttpWebResponse; 35 //读取http返回的数据流 36 Stream ReceiveStream = myResponse.GetResponseStream(); 37 38 using (StreamReader reader = new StreamReader(ReceiveStream, Encoding.UTF8)) 39 { 40 Token = reader.ReadToEnd(); 41 reader.Close(); 42 } 43 myResponse.Close(); 44 45 JObject obj = JObject.Parse(Token); 46 47 var msg = obj.GetValue("msg").ToString(); 48 if (msg != "操作成功") 49 throw new Exception(msg); 50 51 Token = obj.GetValue("token").ToString(); 52 } 53 catch (Exception ex) 54 { 55 throw ex; 56 } 57 return Token; 58 }View Code
2.获取信息接口+表头token串
1 private string GetbjMerial(JObject infostr) 2 { 3 var apiResult = new ResultMessage(); 4 string result = string.Empty; 5 try 6 { 7 string url = "http接口地址"; // 测试系统地址 8 9 var para = JsonConvert.SerializeObject(infostr); 10 11 Encoding encode = System.Text.Encoding.Default; 12 Byte[] arrB = encode.GetBytes(para); 13 14 //获取token 15 string token = this.gettoken(); 16 17 HttpWebRequest Request = HttpWebRequest.Create(url) as HttpWebRequest; 18 Request.Method = "POST"; 19 Request.ContentType = "text/plain"; //"application/json"; 20 Request.Headers.Add("Authorization", token); 21 Request.ContentLength = arrB.Length; 22 //实例化写入请求的参数 23 using (Stream outStream = Request.GetRequestStream()) 24 { 25 outStream.Write(arrB, 0, arrB.Length); 26 outStream.Close(); 27 } 28 29 //接受http响应 30 HttpWebResponse myResponse = Request.GetResponse() as HttpWebResponse; 31 //读取http返回的数据流 32 Stream ReceiveStream = myResponse.GetResponseStream(); 33 34 using (StreamReader reader = new StreamReader(ReceiveStream, Encoding.UTF8)) 35 { 36 result = reader.ReadToEnd(); 37 reader.Close(); 38 } 39 myResponse.Close(); 40 41 } 42 catch (Exception ex) 43 { 44 throw ex; 45 } 46 return result; 47 }View Code
标签:arrB,Encoding,Request,token,HttpWebRequest,string,请求 From: https://www.cnblogs.com/lilt123/p/qfql_2247.html