Netduino home hardware projects downloads community

Jump to content


The Netduino forums have been replaced by new forums at community.wildernesslabs.co. This site has been preserved for archival purposes only and the ability to make new accounts or posts has been turned off.

Christopher Gilmore

Member Since 28 Nov 2010
Offline Last Active Jul 24 2015 12:58 AM
-----

Topics I've Started

Issues Reading Stream from HttpWebResponse

04 January 2015 - 10:46 AM

Hey Guys,

 

I am writing a small Netduino+2 application, which will communicate with the Phillips HUE light bridge controller. This should be a simple task, in that the all I am doing is sending simple Http requests to the bridge (which I can do sucessfully).

 

The problem however, is when I try to process/parse the responses. Right now, I am experiencing three strange issues using the HttpWebResponse and Stream objects.

1. HttpWebResponse.ContentLength is always equal to "-1", even thought there is always body content (application/json content).

2. HttpWebResponse.GetResponseStream() seems to be unstable, in that it will sometimes truncate the response for longer responses (~700 bytes +). Putting in a Thread.Sleep(500) right after seems to help this for some reason. I don't know why.

3. Stream.Read() seems to be unstable, in that it will truncate near the end of stream (return 0) for the larger response.

 

Below is my code. I need this to be able to process around 2KB responses at least. I am running the latest framework 4.3. Anyone have any ideas?

 

Thanks,

Chris

public static string Send(string uri, string method, string body, bool ignoreResponse = true)
        {
            try
            {
                using (HttpWebRequest req = (HttpWebRequest)WebRequest.Create(new Uri("http://" + bridgeIP + "/api/" + bridgeUser + "/" + uri)))
                {
                    req.Method = method;
                    req.ContentType = "text/plain;charset=UTF-8";
                    req.Timeout = 3000; //3s 
                    req.ReadWriteTimeout = 3000;
                    req.KeepAlive = false;
                    if (body != null && body != "")
                    {
                        byte[] buffer = Encoding.UTF8.GetBytes(body);
                        req.ContentLength = buffer.Length;
                        using (Stream PostData = req.GetRequestStream())
                        {
                            PostData.Write(buffer, 0, buffer.Length);
                            PostData.Close();
                        }
                    }
                    else
                    {
                        req.ContentLength = 0;
                    }

                    Debug.Print("Sending " + method + " request to: " + uri);
                    HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

                    string responseString = "";
                    
                    int contentLength = (int)resp.ContentLength;
                    if (!ignoreResponse)// && contentLength > 0)
                    {
                        //Otherwise process response
                        using (Stream responseStream = resp.GetResponseStream())
                        {
                            System.Threading.Thread.Sleep(500); //This seems to help fix the following line (responseStream.Length)
                            int responseLength = (int)responseStream.Length;

                            Debug.Print("Response with length " + responseLength.ToString() + " received. Processing...");
                            if (responseLength <= 0) return null;

                            //write to responseString in chunks of 256 bytes 
                            byte[] c = null;
                            while (true)
                            {
                                c = new byte[256];
                                if (responseStream.Read(c, 0, c.Length) == 0) break;
                                responseString += new string(Encoding.UTF8.GetChars(c));
                            }
                        }
                    }
                    resp.Close();
                    resp.Dispose();
                    req.Dispose();
                    Debug.Print("Response Processed. Length of:" + responseString.Length.ToString());
                    return responseString == "" ? null : responseString;
                }
            }
            catch (Exception e)
            {
                Debug.Print(e.ToString());
            }
            
            return null;
        }

home    hardware    projects    downloads    community    where to buy    contact Copyright © 2016 Wilderness Labs Inc.  |  Legal   |   CC BY-SA
This webpage is licensed under a Creative Commons Attribution-ShareAlike License.