Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# JSON Post using HttpWebRequest

Tags:

json

c#

I am new to JSON and C# and trying to write a code that will perform an http web request POST to get a token. Below is my code but I keep getting 400 bad request. Probably my codes just incorrect and I will appreciate for any helps on this. Below is 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;
    }
like image 326
BanggaDad Avatar asked Mar 16 '16 21:03

BanggaDad


1 Answers

Here is a precise and accurate example of a POST request and reading the response(though without serializing the JSON data). Only mistake I see so far in your code is an incorrect ContentType also we can't see what url you are trying to send the server(but odds are that it is incorrect). Hope it helps you advance.

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 = WebRequest.CreateHttp(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);
            }
        }
    }
}
like image 197
Kent Kostelac Avatar answered Nov 08 '22 20:11

Kent Kostelac