gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 16:10:30 25 4
gpt4 key购买 nike

我正在使用 C# 开发 Windows 应用商店应用程序,我是这个平台的新手(我主要从事 IOS 和 Android 方面的工作)。

我有一个简单的异步方法可以从远程服务器下载原始数据。它工作正常,除了我不断看到来自 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;
}

最佳答案

我转而使用 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;
}

关于c# - 从 WebResponse 类读取时数据过早结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17663715/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com