Search code examples
c#httpwebrequestcompact-frameworkwindows-ce

Windows Ce Compact Framework HttpWebRequest


i am trying to write some data on a controller using rest api.

But something strange is happening. The first 1, 2, 3 writes are fine but than the application freezes and gets timeouts exceptions am i not closing something?

This is the code below:

        WebRequest client = (read) ? HttpWebRequest.Create(ReadUri) : HttpWebRequest.Create(WriteUri);
        client.Method = "POST";
        client.ContentType = "application/json";
        CredentialCache creds = new CredentialCache();
        creds.Add(new Uri(WriteUri), "Basic", new NetworkCredential(*******));
        client.Credentials = creds;
        client.PreAuthenticate = true;
        ((HttpWebRequest)client).AllowWriteStreamBuffering = true;
        client.Timeout = 10000;
        //Skipped all data formatting
        byte[] data = Encoding.UTF8.GetBytes(req);
        client.ContentLength = data.Length;
        Stream dataStream = null; 
        try
        {
            //HttpWebResponse response = (HttpWebResponse)client.GetResponse();
            dataStream = client.GetRequestStream();

            dataStream.Write(data, 0, data.Length);
            dataStream.Flush();
            dataStream.Close();
            dataStream.Dispose();
            dataStream = null;

        }
        catch (WebException we)
        {
            string message = we.Message;
        }
        finally
        {
            client = null;
        }

Solution

  • After you have sent the request, you should process the response and dispose it. If you don't, under the hood the request and its response will remain associated with the connection, and .NET by default only has a few connections available for WebRequests.

    ...
    dataStream.Close();
    dataStream.Dispose();
    dataStream = null;
    using (HttpWebResponse response = (HttpWebResponse)client.GetResponse())
    {
    }