Created
July 18, 2011 03:34
-
-
Save AHartTN/1088495 to your computer and use it in GitHub Desktop.
Generic JSON HTTP POST method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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