从WebResponse类读取数据时过早结束

时间:2013-07-15 20:51:52

标签: c# windows-store-apps webrequest

我正在使用C#开发Windows应用商店应用,我在这个平台上很新(我主要从事IOS和Android)。

我有一个简单的Async方法从远程服务器下载原始数据。它工作正常,除了我一直看到来自WebResponse类的随机不完整读取。这是非常简单的方法,我无法弄清楚它为什么会过早结束。远程服务器工作正常(ios / web / android正常并且正在检索数据)所以我显然在这里做错了。

任何帮助都会很好地解决这个问题。

public async Task<byte[]> doGETRequestAsync(String url)
{
    callSuccess = false;

    byte[] responseFromServer = null;
    try
    {
        WebRequest request = WebRequest.Create(url);    
        request.Method = "GET";
        WebResponse response = await request.GetResponseAsync();

        using (Stream dataStream = response.GetResponseStream())
        {
            responseFromServer = new byte[response.ContentLength];
            int readCount = await dataStream.ReadAsync(responseFromServer, 0, (int)response.ContentLength);
            if (readCount != response.ContentLength)
                throw new IOException("Premature end of data. Expected: " + response.ContentLength + " received: " + readCount);
        }


        response.Dispose();

    }
    catch (HttpRequestException hre)
    {
        Debug.WriteLine("Exception performing network call : " + hre.ToString());
    }
    catch (Exception e)
    {
        Debug.WriteLine("Exception performing network call : " + e.ToString());
    }

    return responseFromServer;
}

1 个答案:

答案 0 :(得分:0)

我转而使用HttpClient和HttpClientHandler,它完美无缺。这也支持存储cookie并在每次通话时重复使用。

这是可以处理GET和POST并将数据作为bytes []数组返回的代码。如果响应是utf8编码的字符串,则可以使用System.Text.Encoding.UTF8.GetString(respBytes,0,respBytes.Length)将字节转换为字符串;

希望它有用

class Network
{
   static CookieContainer cookieJar = new CookieContainer();
   List<KeyValuePair<string, string>> postParameters = new List<KeyValuePair<string, string>>();

   // Add post parameter before calling NetworkRequestAsync for POST calls.
   public void addPostParameter(String key, String value)
   {
       postParameters.Add(new KeyValuePair<string, string>(key, value));

    }

    public async Task<byte[]> NetworkRequestAsync(String url, bool GET_REQUEST)
    {
        callSuccess = false;
        byte[] respBytes = null;
        try
        {
            HttpClientHandler handler = new HttpClientHandler()
            {
                // Use and reuse cookies in the cookiejar 
                CookieContainer = cookieJar
            };

            handler.AllowAutoRedirect = false;
            handler.UseCookies = true;

            HttpClient client = new HttpClient(handler as HttpMessageHandler)
            {
                BaseAddress = new Uri(@url)
            };

            HttpResponseMessage response = null;

            if (GET_REQUEST)
            {
                response = await client.GetAsync(client.BaseAddress);
            }
            else
            {

                HttpContent content = new FormUrlEncodedContent(postParameters);
                //String postparam=await content.ReadAsStringAsync();
                //Debug.WriteLine("Post Param1=" + postparam);

                response = await client.PostAsync(client.BaseAddress, content);

                callSuccess = true;
            }

            respBytes = await response.Content.ReadAsByteArrayAsync();

        }
        catch (Exception e)
        {
            Debug.WriteLine("Exception performing network call : " + e.ToString());
        } 

        return respBytes;
    }

}