8

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;
    }
5
  • 1
    Content-Type is incorrect for a JSON request body. Try "application/json" instead of "x-www-form-urlencoded" (which is for standard form query string data)
    – Quintium
    Mar 16, 2016 at 21:40
  • Thank you Quintium. Probably it was my mistake to use JSON in the request while the content type is for query string data. I've updated the codes below and still get 400 bad request error.
    – BanggaDad
    Mar 16, 2016 at 22:08
  • Could be completely unrelated, but usually authentication data sent in the header, and could this be the reason? Mar 16, 2016 at 22:28
  • Well, that also depends on the API you are posting to. 400 most of the time means, there is something wrong with the data. Hard to say what without knowing the target specification. It may be a missing value, wrong data format (json vs urlencoded), mismatch between Content type and data. Or the developer was just lazy and returns 400 on any error. And many reasons more Mar 17, 2016 at 0:47
  • You will also need to set the Content-Length when using POST.
    – Quintium
    Mar 17, 2016 at 16:20

2 Answers 2

30

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);
            }
        }
    }
}
1
  • 1
    There is now a WebRequest.CreateHttp() constructor you can use to be more explicit and avoid the casting.
    – DanO
    Jul 24, 2019 at 19:06
-3

You have set requestUrl to "some URL". Please try with a web address that exists, in addition to changing the content type to "application/json".

1
  • 1
    I'm quite sure, he used the correct URL in his original Code, as otherwise he would have gotten an DNS error instead of a 400 Bad request. Mar 17, 2016 at 0:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.