C# HttpWebRequest FormData post and return Json
Wednesday, January 24, 2018 Category : ASP.NET, C-sharp.NET 0
public static Result POSTFormData(string url, string identifier, string FormData)
{
// Setup the POST data
//string poststring = String.Format("qrCodeData=90320388203195564382");
Result result = new Result();
try
{
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";
httpRequest.Headers.Add("secret", identifier);
// Convert the post string to a byte array
byte[] bytedata = System.Text.Encoding.UTF8.GetBytes(FormData);
httpRequest.ContentLength = bytedata.Length;
// Create the stream
Stream requestStream = httpRequest.GetRequestStream();
requestStream.Write(bytedata, 0, bytedata.Length);
requestStream.Close();
// Get the response from remote server
HttpWebResponse httpWebResponse = (HttpWebResponse)httpRequest.GetResponse();
Stream responseStream = httpWebResponse.GetResponseStream();
System.Text.StringBuilder sb = new System.Text.StringBuilder();
using (StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8))
{
string line;
while ((line = reader.ReadLine()) != null)
{
sb.Append(line);
}
}
result.ResultState = true;
result.JsonString = sb.ToString();
}
catch (Exception ex)
{
result.ResultState = false;
result.SqlError = ex.Message;
}
return result;
}
object theImg = dt.Rows[0]["Picture"];
if (!DBNull.Equals(theImg, DBNull.Value) && ((byte[])theImg).Length > 0)
{
pictureBox1.BackgroundImage = new ImageHelper().ByteToImage((byte[])theImg);
}