繁体   English   中英

为什么我的C#Web请求没有返回任何内容?

[英]Why isn't my C# web request returning anything?

我遇到一个返回长JSON集(真的很长,2000万个字符)的URL。 只需将网址粘贴到Chrome中,大约需要3分钟即可返回完整的结果集。 不论Chrome中的默认设置如何,它都会多次提示我杀死页面或等待。 但是页面将​​在几分钟后返回。

我正在使用脚本任务从SSIS运行它。 我对C#不太熟悉。 我从一个示例复制/粘贴了此代码:

{

    HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(wUrl);
    httpWReq.Method = "GET";
    httpWReq.ContentType = "application/json";
    httpWReq.Timeout = 300000;
    HttpWebResponse httpWResp = (HttpWebResponse)httpWReq.GetResponse();
    RootObject jsonResponse = null;

    try
    {
        //Get the stream of JSON
        Stream responseStream = httpWResp.GetResponseStream();

        //Deserialize the JSON stream
        using (StreamReader reader = new StreamReader(responseStream))
        {
            //Deserialize our JSON
            DataContractJsonSerializer sr = new DataContractJsonSerializer(typeof(RootObject));
            jsonResponse = (RootObject)sr.ReadObject(responseStream);
        }
    }
    //Output JSON parsing error
    catch (Exception e)
    {
        FailComponent(e.ToString());
    }
    return jsonResponse;

我对wURL字符串是有效的JSON端点表示肯定110%。 当我单步执行代码时,它可能在以下行上等待15秒:

HttpWebResponse httpWResp = (HttpWebResponse)httpWReq.GetResponse();

...然后没有错误地返回... ...但是它没有填充我期望的httpWResp(ContentLength = -1)。 当到达:

jsonResponse = (RootObject)sr.ReadObject(responseStream); 

... jsonResponse保存我的预定义json容器对象,设置为null。 我的网址返回了数千个json数组。

我在responseStream中没有看到任何有趣的属性来表明它实际上包含了什么?

我在这里想念什么?

我无法发布实际的网址,因为它是私人公司的网址。

================================

编辑:我尝试使用一个短得多的字符串的URL,并返回。 因此,似乎与长度有关。 我通过验证器运行了返回值,它成功了……所以可能是一个特殊字符,但我认为可能是长度。

从注释中我们现在知道,从GetResponse()返回的响应对象的StatusCodeOKContentTypeapplication / json; charset = UTF-8-指示服务器已返回数据“ chunked”,即为什么ContentLength = -1。

您应该能够在StreamReader上使用ReadToEnd()方法,如下所示:

//Deserialize the JSON stream
using (StreamReader reader = new StreamReader(responseStream))
    {
        string r = reader.ReadToEnd();

        //Deserialize our JSON
        DataContractJsonSerializer sr = new DataContractJsonSerializer(typeof(RootObject));
        MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(r));
        jsonResponse = (RootObject)sr.ReadObject(ms);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM