簡體   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