HttpWebRequest request for a webapi with oau2authorization,
OAuth 2.0 considerations:
1. When obtaining access_token, use POST
1 private static string GetAuthorization (string username, string password) 2 {3 string authorization = string. format ("{0 }:{ 1}", username, password); 4 5 return "Basic" + Convert. toBase64String (new ASCIIEncoding (). getBytes (authorization); 6}View Code 1 // <summary> 2 // get Token 3 // </summary> 4 // <returns> </returns> 5 private static string OAuthClientCredentialsToken () 6 {7 const string clientId = "8518"; 8 const string clientSecret = "8518"; 9 string result = string. empty; 10 11 HttpWebRequest httpWebRequest = (HttpWebRequest) WebRequest. create (_ baseUrl + "/token"); 12 httpWebRequest. method = "POST"; 13 httpWebRequest. contentType = "Application/x-www-form-urlencoded"; 14 httpWebRequest. accept = "application/json"; 15 httpWebRequest. timeout = 15000; 16 httpWebRequest. keepAlive = false; 17 httpWebRequest. allowAutoRedirect = true; 18 // httpWebRequest. headers. add ("Accept-Language", "zh-cn"); 19 // httpWebRequest. headers. add ("Accept-Encoding", "gzip, deflate"); 20 // httpWebRequest. userAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Wind The ows NT 5.2 ;. net clr 1.1.4322) "; 21 httpWebRequest. headers. add ("Authorization", GetAuthorization (clientId, clientSecret); 22 // Credentials23 httpWebRequest. credentials = CredentialCache. defaultCredentials; 24 // post parameter 25 StringBuilder postParam = new StringBuilder (); 26 Dictionary <string, string> parameters = new Dictionary <string, string >{{ "grant_type ", "client_credentials" }}; 27 int I = 0; 28 Each (KeyValuePair <string, string> parameter in parameters) 29 {30 if (I> 0) 31 postParam. append ("&"); 32 postParam. appendFormat ("{0 }={ 1}", parameter. key, HttpUtility. urlEncode (parameter. value); 33 I ++; 34} 35 36 byte [] postData = Encoding. UTF8.GetBytes (postParam. toString (); 37 httpWebRequest. contentLength = postData. length; 38 39 try40 {41 Stream requesStream = httpWebRequest. getRequestStream (); 42 re QuesStream. write (postData, 0, postData. length); 43 requesStream. close (); 44 45 WebResponse response = httpWebRequest. getResponse (); 46 Stream stream = response. getResponseStream (); 47 if (stream! = Null) 48 {49 using (StreamReader reader = new StreamReader (stream, Encoding. UTF8) 50 {51 result = reader. readToEnd (); 52 reader. close (); 53} 54 stream. close (); 55} 56} 57 catch (WebException ex) 58 {59 throw new Exception (ex. message); 60} 61 return! String. IsNullOrWhiteSpace (result )? JObject. Parse (result) ["access_token"]. Value <string> (): result; 62}View Code
2. To access the Api to be authorized, use the http/https protocol and add the access token Header.
3. The Header Format is "Authorization: Bearer access_token", with a space behind Bearer
1 /// <summary> 2 /// HttpGet 3 /// </summary> 4 /// <param name = "url"> </param> 5 /// <param name = "token"> </param> 6 // <param name = "contentType"> </param> 7 /// <returns> </returns> 8 private static string HttpGet (string url, string token, string contentType = "application/x-www-form-urlencoded") 9 {10 HttpWebRequest httpWebRequest = (HttpWebRequest) WebRequest. create (url); 11 httpWebRequest. method = "GET"; 12 httpWebRequest. contentType = contentType; 13 httpWebRequest. accept = "application/json"; 14 httpWebRequest. timeout = 15000; 15 httpWebRequest. allowAutoRedirect = false; 16 // Bearer + space 17 httpWebRequest. headers. add ("Authorization", "Bearer" + token); 18 httpWebRequest. credentials = CredentialCache. defaultCredentials; 19 20 string result = null; 21 try22 {23 WebResponse response = httpWebRequest. GetResponse (); 24 Stream responseStream = response. GetResponseStream (); 25 if (responseStream! = Null) 26 {27 using (StreamReader streamReader = new StreamReader (responseStream, Encoding. UTF8) 28 {29 result = streamReader. readToEnd (); 30 streamReader. close (); 31} 32} 33} 34 catch (Exception ex) 35 {36 throw new Exception (ex. message); 37} 38 return result; 39}View Code