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.
Photo

Issues Reading Stream from HttpWebResponse

HttpWebResponse Stream ContentLength WebResponse Json

  • Please log in to reply
1 reply to this topic

#1 Christopher Gilmore

Christopher Gilmore

    Member

  • Members
  • PipPip
  • 12 posts
  • LocationBurlington, MA

Posted 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;
        }


#2 Mario Vernari

Mario Vernari

    Advanced Member

  • Members
  • PipPipPip
  • 1768 posts
  • LocationVenezia, Italia

Posted 04 January 2015 - 01:35 PM

The Thread.Sleep(500) at the beginning looks useless. Rather, add a Thread.Sleep(100) inside the while.

 

Moreover, inside the same "while" you're creating a new byte-array object on every cycle: that's causes an unnecessary yet expensive memory management. Create it once outside the "while": there's no need to create a new one all the times.

 

Finally, instead of reading always a lot of useless bytes (256), consider asking the stream how many are still to pull off, and use that value in the "Read" method.

Another way is the following:

https://github.com/h...erviceClient.cs

 

Good luck.


Biggest fault of Netduino? It runs by electricity.





Also tagged with one or more of these keywords: HttpWebResponse, Stream, ContentLength, WebResponse, Json

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

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.