Windows Ce Compact Framework HttpWebRequest

时间:2017-05-16 07:05:03

标签: c# httpwebrequest compact-framework windows-ce

我正在尝试使用controllerrest api上写一些数据。

但是发生了一些奇怪的事情。第一次,第2次,第3次写入是好的,但是应用程序冻结并获得超时异常,我不会关闭某些内容吗?

这是下面的code

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

1 个答案:

答案 0 :(得分:2)

发送请求后,您应该处理响应并进行处理。如果不这样做,那么请求及其响应将保持与连接关联,默认情况下,.NET只有一些可用于WebRequest的连接。

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