I am using HttpClient to send a POST request to an external API and I know I'm sending the correct payload and headers and everything because it works sometimes but other times it returns an empty string response. It always returns a 200 status code. Changing it to asynchronous is not an option so my question is, how do I run this synchronously and reliably get a response back?
This is the method that I've used in a number of other places in my application for GETs and POSTs and it works perfectly fine every time:
HttpClient client = new HttpClient { BaseAddress = new Uri("url")
client.DefaultRequestHeaders.Add("X-Authorization", "Bearer " + authToken);
var input = new {json object};
var serializerSettings = new JsonSerializerSettings();
serializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
var json = JsonConvert.SerializeObject(input, serializerSettings);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var result = client.PostAsync("api/Create", data).Result;
if (result.IsSuccessStatusCode)
{
var jsonStringResult = result.Content.ReadAsStringAsync().Result;
var response = JsonConvert.DeserializeObject<ApiResponse>(jsonStringResult);
// response is null....sometimes
}
Other methods that I've tried from scouring other forum posts and blogs:
var postTask = client.PostAsync("api/Create", data);
postTask.Wait();
var result = postTask.Result;
if (result.IsSuccessStatusCode)
{
var jsonTask = result.Content.ReadAsStringAsync();
jsonTask.Wait();
var jsonStringResult = jsonTask.Result;
var response = JsonConvert.DeserializeObject<ApiResponse>(jsonStringResult);
// response is null....sometimes
}
and
var result = client.PostAsync("api/Create", data).GetAwaiter().GetResult();
if (result.IsSuccessStatusCode)
{
var jsonStringResult = result.Content.ReadAsStringAsync().GetAwaiter().GetResult();
var response = JsonConvert.DeserializeObject<ApiResponse>(jsonStringResult);
// response is null....sometimes
}
and
byte[] byteArray = Encoding.UTF8.GetBytes(json);
var request = (HttpWebRequest)WebRequest.Create("url");
request.Method = "POST";
request.ContentType = "application/json; charset=UTF-8";
request.Accept = "application/json";
request.ContentLength = byteArray.Length;
request.Headers.Add("X-Authorization", "Bearer" + authToken);
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
dataStream.Close();
response.Close();
var responseObj = JsonConvert.DeserializeObject<ApiResponse>(responseFromServer);
// resonseObj is null...sometimes
All four methods work some of the time but I need this to be more reliable. Deadlocks are not a concern at this time. Any help is appreciated!