Simple implementation of request the 3rd party web apis. This function make the request to suplied url of api and returns data in the string. For more details check this out..
Step 1: Add the following method in your c# class file.
/// <summary>
/// Calling 3rd party web apis.
/// </summary>
/// <param name="destinationUrl"></param>
/// <param name="methodName"></param>
/// <param name="requestJSON"></param>
/// <returns></returns>
public string MakeWebRequest(string destinationUrl, string methodName, string contentType = "", string requestJSON = "")
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
request.Method = methodName;
if (methodName == "POST")
{
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(requestJSON);
request.ContentType = contentType;
request.ContentLength = bytes.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
}
return null;
}
catch (WebException webEx)
{
return webEx.Message;
}
}
Step 2: You can use the above method as following:
For Get request:
string tokenResponse = MakeWebRequest(url, "GET");
For POST request:
string tokenResponse = MakeWebRequest(url, "POST","application/json",new{id=1,name="test"});
No comments:
Post a Comment