C#後臺獲取token訪問webapi
阿新 • • 發佈:2020-09-22
api需要先獲取token時
public static string PostRequest(string Url) { string appId = ""; string appSecret = ""; string app = appId + ":" + appSecret; string Auth = EncodeBase64("utf-8", app); //64位加密 方法需要自己寫 HttpWebRequest webRequest= (HttpWebRequest)WebRequest.Create(Url); webRequest.Method = "post"; webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.Timeout = 20000; webRequest.Headers.Add("Authorization", "Basic " + Auth); //header部分 NameValueCollection outgoingQueryString = HttpUtility.ParseQueryString(String.Empty); outgoingQueryString.Add("引數", "引數"); outgoingQueryString.Add("引數", "引數"); string postData = outgoingQueryString.ToString(); byte[] byteArray = Encoding.UTF8.GetBytes(postData);//引數轉成位元組 using (Stream reqStream = webRequest.GetRequestStream()) { reqStream.Write(byteArray,0, byteArray.Length); } HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { retuen reader.ReadToEnd() ;
} }
使用token訪問api
public static string request(string url,string Authorization) { HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url); webRequest.Method = "get"; webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.Timeout = 20000; webRequest.Headers.Add("Authorization", Authorization); HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) {
return reader.ReadToEnd();
}
}