I have written a code to call a website which returns some data. I have used HttpWebRequest.GetResponse()
method. When I hit the url in browser, it returns data. However in my C# code, sometimes it returns data, sometimes it do not return anything.
The request is not throwing any error such as time-out or access denied. It returns nothing. If I use debuggers in code, it returns data.
Code is as below;
HttpWebRequest clnt = (HttpWebRequest)HttpWebRequest.Create(restURL);
var resp = clnt.GetResponse();
if ((resp.ContentLength > 0))
{
using (System.IO.StreamReader str = new System.IO.StreamReader(resp.GetResponseStream()))
{
if (str != null)
{
string response = str.ReadToEnd();
str.Close();
return response;
}
}
}
Please help me if I am missing anything.
Have you tried giving the Method and Content type?
clnt.Method = "POST";
clnt.ContentType = "application/x-www-form-urlencoded";
It will come like this :
HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(url);
httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoded";
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
return responseString;
Hope this helps you!