You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用HttpWebRequest读取API响应时遇意外EOF流错误排查

问题:HttpWebRequest调用API时出现EOF错误

我正在开发一个使用HttpWebRequest从API https://restcountries.com/v3.1/all获取国家数据的应用程序。几周前代码运行正常,但现在抛出如下错误:

System.IO.IOException: 'Received an unexpected EOF or 0 bytes from the transport stream.'

该错误在调用responseStream.ReadToEnd()读取响应体时触发,我未对代码做任何修改,因此不确定问题原因。以下是我使用的代码:

public class CountryRepository
{
    private List<Country> _Countries = new List<Country>();

    private string url = "https://restcountries.com/v3.1/all";

    public List<Country> GetCountries()
    {
        string json = CallRestMethod(url);
        JArray jsonArray = JArray.Parse(json); // Parse JSON

        foreach (JObject item in jsonArray)
        {
            _Countries.Add(new Country
            {
                Code = (string)item["cca2"],
                Name = (string)item["name"]?["common"],
                Capital = item["capital"] != null && item["capital"].Type == JTokenType.Array
                    ? (string)item["capital"].First
                    : null,
                Population = (int)(item["population"] ?? 0),
                Area = item["area"]?.Type == JTokenType.Null ? 0 : (float)(item["area"]),
                Region = (string)item["region"],
            });
        }

        return _Countries;
    }

    public static string CallRestMethod(string url)
    {
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
        webRequest.Method = "GET";
        webRequest.ContentType = "application/x-www-form-urlencoded";
        HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
        Encoding encoding = Encoding.GetEncoding("utf-8");
        using (StreamReader responseStream = new
        StreamReader(webResponse.GetResponseStream(), encoding))
        {
            string result = responseStream.ReadToEnd();
            webResponse.Close();
            return result;
        }
    }
}

我已在Postman中验证该API端点可正常工作,也尝试增加超时值并设置KeepAlive = false。直接打开该URL时,出现如下错误:

"SyntaxError: JSON.parse: unterminated string at line 1 column 477495 of the JSON data"

想了解使用HttpWebRequest读取响应流时出现该错误的可能原因是什么?


可能的原因及解决方向

1. TLS版本不兼容

HttpWebRequest默认可能使用TLS 1.0/1.1等旧版本协议,而restcountries.com可能已禁用这些过时协议,强制要求TLS 1.2或更高版本。在创建请求前添加以下代码指定TLS版本:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;

2. 未处理响应压缩

API可能返回了gzip/deflate压缩的内容,但你的代码没有启用自动解压,导致读取到的是压缩后的二进制数据,进而引发截断或解析错误。添加自动解压配置:

webRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

3. HttpWebRequest的兼容性局限

HttpWebRequest已被标记为过时,对现代API的响应处理(如分块传输、动态内容编码)支持不如HttpClient完善。建议替换为HttpClient,代码示例:

public static async Task<string> CallRestMethodAsync(string url)
{
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;
    using (HttpClient client = new HttpClient())
    {
        client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
        client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate"));
        return await client.GetStringAsync(url);
    }
}

4. 网络层面的响应截断

你的网络环境(如代理、防火墙)可能在传输过程中截断了响应内容,导致JSON不完整。可以尝试切换网络环境,或检查代理配置是否正确应用到请求中。


内容的提问来源于stack exchange,提问作者Sodium Chloride121

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 18:15:10