C # JSON Post using HttpWebRequest

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; } 
+5
source share
2 answers

Here is an accurate and accurate example of a POST request and reading a response (although without serializing JSON data). Only the error that I see so far in your code is the wrong ContentType, we can’t see what URL you are trying to send to the server (but the probability that it is incorrect). Hope this helps you move forward.

 using System; using System.Collections.Generic; using System.Net; using System.IO; namespace SExperiment { class MainClass { public static void Main(string[] args) { try{ string webAddr="http://gurujsonrpc.appspot.com/guru"; var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr); httpWebRequest.ContentType = "application/json; charset=utf-8"; httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { string json = "{ \"method\" : \"guru.test\", \"params\" : [ \"Guru\" ], \"id\" : 123 }"; streamWriter.Write(json); streamWriter.Flush(); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var responseText = streamReader.ReadToEnd(); Console.WriteLine(responseText); //Now you have your response. //or false depending on information in the response } }catch(WebException ex){ Console.WriteLine(ex.Message); } } } } 
+15
source

You set requestUrl to "some URL". Try using an existing web address in addition to changing the content type to "application / json".

-2
source

Source: https://habr.com/ru/post/1245196/


All Articles