HTTP Post Request returns 400 C #

I am trying to make a request to send http to get an api token. If successful, it should return the string values ​​of the access token, such as a token (bearer) and expires_in.

The code that I have is the general one that I expected to see. But for some reason, it throws an exception 400 "The remote server returned an error." Bad request. "I tried to fix everything, while the result did not change.

When I debug the code and see the result in the output window, there is an exception from the data stream saying that "this stream does not support search operations"

Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();

My doubt is that this is due to postData, how it is encoded. My client secret is something like:

g / gOvqf5R + FTZZXbwsCbp0WsQjF9B0bl87IBQ8VAJ2Q =

Does it encode characters in secret so that it creates a bad request?

I also tried this on POSTMAN and it gave the result, so nothing happens with the api. It returns to the contents of the request again. This is a console application. I am inserting my code below and I am grateful for your help in advance.

public static APIModel GenerateApiKey()
    {
        var appSettings = ConfigurationManager.AppSettings;

        try
        {
            var urlToCall = string.Format("https://app.example.com/token");
            var uri = new Uri(urlToCall);

            var request = (HttpWebRequest)WebRequest.Create(uri);
            request.Method = "POST";

            string postData = "grant_type=client_credentials&client_id=" + appSettings["my_client_id"] + "&client_secret=" + appSettings["my_client_secret"];
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;


            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            var response = (HttpWebResponse)request.GetResponse();

            APIModel bearerToken;

            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                string jsonFromServer = sr.ReadToEnd();
                bearerToken = JsonConvert.DeserializeObject<APIModel>(jsonFromServer); 
            }

            response.Close();

            return bearerToken;

        }
        catch (Exception e)
        {
            throw new Exception("Error getting a response from API  " + e.Message);
        }

    }
+4
source share
2 answers

400 - , . - , , . , - - URL. , , =. . , :

var postItems = new List<KeyValuePair<string, string>>
{
    new KeyValuePair<string, string>("grant_type", "client_credentials"),
    new KeyValuePair<string, string>("client_id", "client_credentials"),
    new KeyValuePair<string, string>("client_secret", "client_credentials"),
};

string postData = string.Join("&", 
    postItems.Select (kvp => 
        string.Format("{0}={1}", kvp.Key, HttpUtility.UrlEncode(kvp.Value))));
+2

. postData:

string postData = "grant_type=client_credentials&client_id=" + HttpUtility.UrlEncode(appSettings["my_client_id"]) + "&client_secret=" + HttpUtility.UrlEncode(appSettings["my_client_secret"]);
0

All Articles