2

I am developing a Windows Store App using C# and I am very new at this platform (I have been primarily working on IOS and Android).

I have a simple Async method to download raw data from a remote server. It works ok except that I keep seeing random incomplete reads from the WebResponse class. It is pretty simple method and I cant figure out why it would end prematurely. The remote server is working fine ( ios/web/android fine and are retrieving data) so I am obviously doing something wrong here.

Any help will be great in figuring out this problem.

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

1 回答 1

0

我切换到使用 HttpClient 和 HttpClientHandler 并且效果很好。这还支持存储 cookie 并在每次调用时重复使用它。

这是可以处理 GET 和 POST 并将数据作为字节数组返回的代码[]。如果响应是 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;
    }

}

于 2013-07-16T21:33:26.670 回答