简体   繁体   中英

Sending Data to SalesForce by HttpClient(C#) Post Method, Not Working

I am trying to send a json Object to SalesFroce using HttpClient, but this behaves Weirdly...

First i login in to Salesforce Via following code

var sendPaylod = new Dictionary<string, string>
{
{"grant_type","password"},
{"client_id",s_clientId},
{"client_secret",s_clientSecrate},
{"username",s_username},
{"password",s_password}
};

HttpClient auth = new HttpClient();
HttpContent content = new FormUrlEncodedContent(sendPaylod);
HttpResponseMessage response = await auth.PostAsync(s_tokenRequestEndpointUrl, content);
string msg = await response.Content.ReadAsStringAsync();
Console.WriteLine(msg);
string authToken = (String)jsonObj["access_token"];

Now I have got authToken as a bearer token to send data to salesFroce

I am doing that by Following

var obj = new { Director = "003e000001MQYjB", 
                CityName = "XXAA", 
                CityId = "000000",  
                RegionName = "India", 
                RegionId = "00000" };
 
string c_url = "URL to which data will sent";
var c_Obj = JsonConvert.SerializeObject(obj);
var c_content = new System.Net.Http.StringContent(c_Obj, Encoding.UTF8, "application/json");

HttpClient c_client = new HttpClient();
c_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization","Bearer "+authToken);

HttpContent c_content = new StringContent(c_Obj, Encoding.UTF8, "application/json");
c_content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var c_response = await c_client.PostAsync(c_url, content);
var c_msg = await c_response.Content.ReadAsStringAsync();


Now Am getting Following Response...

"status": "success",
"recordId": "",
"message": ""

If i Use Same Bearer Token in Postman and Send same Json Object I receive Following response.

"status": "success",
"recordId": "a16e0000002qV6aE",
"message": ""

Please Help in this matter.

Fix the next errors:

Change:

var c_response = await c_client.PostAsync(c_url, content); 

to:

var contentType = new MediaTypeWithQualityHeaderValue("application/json");
c_client.DefaultRequestHeaders.Accept.Add(contentType);
var c_response = await c_client.PostAsync(c_url, c_content); 
var c_msg = await c_response.Content.ReadAsStringAsync();
var result =JsonConvert.DeserializeObject<your return class>(c_msg);

and change your authorization to:

 c_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken ); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM