Skip to content

Instantly share code, notes, and snippets.

@victormejia
Last active August 29, 2015 14:07
Show Gist options
  • Save victormejia/e58de101ba46bb0e89b7 to your computer and use it in GitHub Desktop.
Save victormejia/e58de101ba46bb0e89b7 to your computer and use it in GitHub Desktop.
public static string PostRequest(Uri serviceReqUrl, string jsonData, Dictionary<string, string> additionalHeaders, out System.Net.HttpStatusCode statusCode)
{
HttpResponseMessage response = null;
try
{
using (HttpClient client = new HttpClient())
{
HttpContent content = new System.Net.Http.StringContent(jsonData, System.Text.Encoding.UTF8, "application/json");
if (additionalHeaders != null)
{
foreach (var k in additionalHeaders.Keys)
{
string val = string.Empty;
additionalHeaders.TryGetValue(k, out val);
client.DefaultRequestHeaders.Add(k, val);
}
}
response = client.PostAsync(serviceReqUrl, content).Result;
statusCode = response.StatusCode;
return response.Content.ReadAsStringAsync().Result;
}
}
catch (HttpRequestException e)
{
Trace.TraceError(string.Format("PostRequest failed. Request URL = {0}, Response Status Code = {1}", serviceReqUrl, (int)response.StatusCode));
Trace.TraceError(e.StackTrace);
throw e;
}
}
public static string PostRequest(Uri serviceReqUrl, string jsonData, Dictionary<string, string> additionalHeaders = null)
{
HttpResponseMessage response = null;
try
{
using (HttpClient client = new HttpClient())
{
HttpContent content = new System.Net.Http.StringContent(jsonData, System.Text.Encoding.UTF8, "application/json");
if (additionalHeaders != null)
{
foreach (var k in additionalHeaders.Keys)
{
string val = string.Empty;
additionalHeaders.TryGetValue(k, out val);
client.DefaultRequestHeaders.Add(k, val);
}
}
response = client.PostAsync(serviceReqUrl, content).Result;
response.EnsureSuccessStatusCode();
return response.Content.ReadAsStringAsync().Result;
}
}
catch (HttpRequestException e)
{
Trace.TraceError(string.Format("PostRequest failed. Request URL = {0}, Response Status Code = {1}", serviceReqUrl, (int)response.StatusCode));
Trace.TraceError(e.StackTrace);
throw e;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment