Skip to content

Instantly share code, notes, and snippets.

@AHartTN
Created July 18, 2011 03:34
Show Gist options
  • Save AHartTN/1088495 to your computer and use it in GitHub Desktop.
Save AHartTN/1088495 to your computer and use it in GitHub Desktop.
Generic JSON HTTP POST method
public T JsonPost<T>(string url, string strJson)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/json; charset=utf-8";
request.Accept = "application/json, text/javascript, */*";
request.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(strJson);
request.ContentLength = byteArray.Length;
using (Stream s = request.GetRequestStream())
{
s.Write(byteArray, 0, byteArray.Length);
}
string json = "";
WebResponse response = null;
try
{
response = request.GetResponse();
}
catch (WebException e)
{
response = e.Response;
}
catch (Exception e)
{
MessageBox.Show(e.Message, "An error has occurred!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (response != null)
{
Stream stream = response.GetResponseStream();
if (stream != null)
using (StreamReader sr = new StreamReader(stream))
{
while (!sr.EndOfStream)
{
json += sr.ReadLine();
}
}
}
JavaScriptSerializer jss = new JavaScriptSerializer();
T result = jss.Deserialize<T>(json);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment