从带有progressbar的URL下载Json文件

时间:2018-05-15 13:08:20

标签: c# json download progress-bar httpwebresponse

我需要从url下载大型json文件。它使用post方法,带参数,用户名,密码等。

由于需要很长时间,我尝试设置一个进度条,这样用户就可以看到它走了多远,剩下多少。

问题

我无法在下载之前从url检索Json文件的内容长度。请参阅以下代码中注释的错误。有什么建议吗?

public void downloadJson(string Url, string UserName, string Password, string FileDownload)
{
    HttpWebRequest httpRequest;
    HttpWebResponse httpResponse;
    int Size;

    var json = string.Format("{{\"user\":\"{0}\",\"pwd\":\"{1}\",\"DS\":\"KG\"}}", UserName, Password);

    httpRequest = (HttpWebRequest)WebRequest.Create(Url);
    httpRequest.Method = WebRequestMethods.Http.Post;

    httpRequest.ContentLength = json.Length;
    httpRequest.ContentType = "application/json";
    httpRequest.Timeout = 600 * 60 * 1000;

    var data = Encoding.ASCII.GetBytes(json); // or UTF8

    using (var s = httpRequest.GetRequestStream())
    {
        s.Write(data, 0, data.Length);
        s.Close();
    }

    httpResponse = (HttpWebResponse)httpRequest.GetResponse();
    Size = (int)httpResponse.ContentLength;
    Stream rs = httpResponse.GetResponseStream();

    //**********************************************
    //Here is the error
    //the below progress bar would never work
    //Because Size returned from above is always -1
    //**********************************************
    progressBar.Invoke((MethodInvoker)(() => progressBar.Maximum = Size));

    using (FileStream fs = File.Create(FileDownload))
    {
        byte[] buffer = new byte[16 * 1024];
        int read;
        int position;

        using (rs)
        {
            while ((read = rs.Read(buffer, 0, buffer.Length)) > 0)
            {
                fs.Write(buffer, 0, read);
                position = (int)fs.Position;
                progressBar.Invoke((MethodInvoker)(() => progressBar.Value = position));
                Console.WriteLine ("Bytes Received: " + position.ToString());
            }
        }

        fs.Close();
    }

1 个答案:

答案 0 :(得分:0)

错误可能在这里;

Size =(int)httpResponse.ContentLength;

我相信当你宣布的时候  int尺寸; 您想要分配整数数据类型Size

但似乎Size的行为不像整数数据类型。

尝试将尺寸更改为siz之类的东西,然后再试一次。