This post shows how to make HttpWebRequest from Asp.Net page using c#. Here, the requirement is to call an external API with Custom headers and sending json data in the page_load method. Reading the Html response from the stream and write it on the Aspx page. Gluid is the Global Unique Identifier generated in c#.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL + "?pID=" + pID);
NameValueCollection nameValueCollection = new NameValueCollection
{
{ "firstName", firstName },
{ "lastName", lastName },
{ "x-requestKey", Gluid },
};
request.Headers.Add(nameValueCollection);
request.Accept = "application/json";
request.ContentType = "application/json";
request.Method = "POST";
request.AllowAutoRedirect = true;
byte[] bytes = Encoding.ASCII.GetBytes(dataSent);
request.ContentLength = bytes.Length;
Stream os = request.GetRequestStream();
os.Write(bytes, 0, bytes.Length); //Push it out there
os.Close();
Stream responseStream = httpWebResponse.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
string html = streamReader.ReadToEnd();
Response.Write(html);
dataSent is the is json data read from a json file and sent as bytes.
For generating Gluid, use the following C# code:
public string GetUniqueIdentifier()
{
var guid = Guid.NewGuid().ToString();
return guid;
}
For similar Http POST request using jquery ajax, check out this post.
Nice article!
LikeLike