I am new to JSON and C # and am trying to write code that will execute an HTTP POST request to get a token. Below is my code, but I keep getting 400 bad requests. Probably my codes are simply incorrect, and I will be grateful for any help in this. Below are my codes:
static public string GetAuthorizationToken() { string token = string.Empty; string requestUrl = "some URL"; HttpWebRequest httpWebRequest = WebRequest.Create(requestUrl) as HttpWebRequest; httpWebRequest.Method = "POST"; httpWebRequest.ContentType = "x-www-form-urlencoded"; Dictionary<string, string> postParameters = new Dictionary<string, string>(); postParameters.Add("grant", "some credentials"); postParameters.Add("id", "1234123411"); postParameters.Add("secret", "1234123411"); postParameters.Add("scope", "abcd"); string postData = ""; foreach (string key in postParameters.Keys) { postData += WebUtility.UrlEncode(key) + "=" + WebUtility.UrlEncode(postParameters[key]) + "&"; } byte[] data = Encoding.ASCII.GetBytes(postData); httpWebRequest.ContentLength = data.Length; Stream requestStream = httpWebRequest.GetRequestStream(); requestStream.Write(data, 0, data.Length); requestStream.Close(); TokenResponse tokenResponse = new TokenResponse(); using (HttpWebResponse response = httpWebRequest.GetResponse() as HttpWebResponse) { if (response.StatusCode != HttpStatusCode.OK) throw new Exception(String.Format( "Server error (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription)); DataContractJsonSerializer responseSerializer = new DataContractJsonSerializer(typeof(TokenResponse)); Stream responseStream = response.GetResponseStream(); object objResponse = responseSerializer.ReadObject(responseStream); tokenResponse = objResponse as TokenResponse; response.Close(); if (tokenResponse != null) { return tokenResponse.accessToken; } } return token; }
source share