locked
How to read partial response content from the internet using HttpClient?

    Question

  • I try to download file with custom header (Authentication header). 

    I choose HttpClient because HttpWebRequest can't custom header.

    When I download content from the internet , api read all content not read partial content.

    Example Code

    HttpClientHandler aHandler = new HttpClientHandler();
    aHandler.ClientCertificateOptions = ClientCertificateOption.Automatic;
    HttpClient aClient = new HttpClient(aHandler);
    aClient.DefaultRequestHeaders.ExpectContinue = false;
    HttpResponseMessage response = await aClient.GetAsync(
        url)
    
    
    Stream stream = await response.Content.ReadAsStreamAsync();
    IInputStream inputStream = stream.AsInputStream();

    I would like to read partial content same using HttpWebRequest as code below.

    Read Partial Code

    using (var responseStream = await request.GetStreamAsync(prefix+path))
                    {}

    Friday, August 8, 2014 8:52 AM

Answers

  • Hi Korawit,

    You can use RangeHeaderValue to set the request header. http://msdn.microsoft.com/en-us/library/system.net.http.headers.rangeheadervalue(v=vs.118).aspx.

    Code may like below:

    string url = "Http://******";
    
                int size = 1000;
    
                using (var httpclient = new HttpClient())
    
                {
    
                    httpclient.DefaultRequestHeaders.Range = new RangeHeaderValue(0, size);
    
                    var response = await httpclient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
    
                    using (var stream = await response.Content.ReadAsStreamAsync())
    
                    {
    
                        var bytes = new byte[size];
    
                        var bytesread = stream.Read(bytes, 0, bytes.Length);
    
                        stream.Close();
    
                    }
    
                }
    

    Try it and let me know the result.

    Regard,


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Monday, August 11, 2014 3:35 AM
    Moderator