Leslie Leslie - 18 days ago 7
C# Question

C# POST to OAUTH2 with formdata

I have used Chrome Advanced Rest Client (ARC) to get the access token for my API call. I am now trying to take what I have working there and convert it to a POST call in my SSIS Script Component.

enter image description here

I have 4 values that I need to include in the data form section of the post.

grant_type = client_credentials

and our partner_id, client_id and client_secret.

How/where do I enter this information in my request? Here is the code I have tried to use. I have another section that does a GET which works when I hard code the token. I am trying to get this POST call to get a new token to use in the GET.

private TokenObject GetWebServiceToken(string wUrl)

{

string grant_type = "client_credentials";
string partner_id = "our partner_id";
string client_id = "our client_id";
string client_secret = "our encoded string";

HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(wUrl);

httpWReq.Method = "POST";

httpWReq.ContentType = "application/x-www-form-urlencoded";

HttpWebResponse httpWResp = (HttpWebResponse)httpWReq.GetResponse();

TokenObject jsonResponse = null;


try

{

//Get the stream of JSON

Stream responseStream = httpWResp.GetResponseStream();

//Deserialize the JSON stream

using (StreamReader reader = new StreamReader(responseStream))

{ //Deserialize our JSON

DataContractJsonSerializer sr = new DataContractJsonSerializer(typeof(TokenObject));

jsonResponse = (TokenObject)sr.ReadObject(responseStream);

}

}

//Output JSON parsing error

catch (Exception e)

{

FailComponent(e.ToString());

}

return jsonResponse;
}

Answer

The body of a application/x-www-form-urlencoded request is just text encoded and formatted in a way similar to how query strings parameters are.

You should be able to create and send your request by replacing this part:

httpWReq.Method = "POST";

httpWReq.ContentType = "application/x-www-form-urlencoded";

HttpWebResponse httpWResp = (HttpWebResponse)httpWReq.GetResponse();   

With the following code:

var postData = "grant_type=" + HttpUtility.UrlEncode(grant_type);
postData += "&partner_id=" + HttpUtility.UrlEncode(partner_id);
postData += "&client_id=" + HttpUtility.UrlEncode(client_id);
postData += "&client_secret=" + HttpUtility.UrlEncode(client_secret);

var body = Encoding.ASCII.GetBytes(postData);

httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoded";
httpWReq.ContentLength = body.Length;

using (var stream = httpWReq.GetRequestStream())
{
    stream.Write(body, 0, body.Length);
}

HttpWebResponse httpWResp = (HttpWebResponse)httpWReq.GetResponse(); 

// response deserialization logic