Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpWebRequest GetResponse() not returning anything

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.

like image 946
Vijay Balkawade Avatar asked Feb 23 '26 20:02

Vijay Balkawade


1 Answers

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!

like image 67
user3222297 Avatar answered Feb 25 '26 10:02

user3222297



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!