0

I am working getting data using HttpWebRequest and run into stream not readable error using the below code.

        JavaScriptSerializer jss = new JavaScriptSerializer();
        string getUrl = "http://url.com";
        var getdata = "";

        HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(getUrl);
        webrequest.Method = "GET";
        webrequest.ContentType = "application/json";
        webrequest.ContentLength = data.Length;

        using (HttpWebResponse webresponse = (HttpWebResponse)request.GetResponse())
        using (Stream stream = webresponse.GetResponseStream())
        using (StreamReader reader = new StreamReader(stream)) //stream not readable error
        {
            getdata = reader.ReadToEnd();
        }

        dynamic getjsondata = jss.Deserialize<dynamic>(getdata);

Not sure where I am doing it wrong.

1 Answer 1

2

Don't supply ContentType or ContentLength for an HTTP Get, the server does that in the response.

In your first using statement, you're calling a different request object.

Try this (no exception handling included):

        JavaScriptSerializer jss = new JavaScriptSerializer();
        string getUrl = "http://url.com";
        var getdata = "";

        HttpWebRequest webRequest = WebRequest.CreateHttp(getUrl);
        //webrequest.Method = "GET"; // GET is the default.

        using (var webResponse = webRequest.GetResponse())
        using (var reader = new StreamReader(webResponse.GetResponseStream()))
        {
            getdata = reader.ReadToEnd();
        }

        dynamic getjsondata = jss.Deserialize<dynamic>(getdata);

You could add an accept header if needed by the endpoint though:

webRequest.Accept = "application/json";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.