locked
HttpClient and Core RRS feed

  • Question

  • User1525382536 posted

    I am trying to get an image size from a web site using HttpClient on Core Ver2.0.

    I am doing :

    private static readonly string browserVer = "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36";
    httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", browserVer);
    HttpResponseMessage response = await httpClient.gets(url); 
    
    

    but when i check the Content-Length header but it not exist.

    should i add some settings for the request.

    Thursday, June 11, 2020 12:14 PM

All replies

  • User475983607 posted

    Did the request return anything?  What is gets()?  Are there any exceptions?  Try setting a break point and stepping through the code.

    Thursday, June 11, 2020 12:59 PM
  • User-474980206 posted

    Sending a content length header is optional. Often you need to read the body stream to get the length.

    Thursday, June 11, 2020 2:34 PM
  • User1525382536 posted

    it was under response content

    (long)response.Content.Headers.ContentLength

    Thursday, June 11, 2020 3:07 PM
  • User-474980206 posted

    yes, but the sender of the response, is not required to send the length. They can use a FIN instead.

    Thursday, June 11, 2020 3:16 PM
  • User1525382536 posted

    what do you mean by FIN?

    Thursday, June 11, 2020 3:42 PM
  • User475983607 posted

    FIN is a packet used to terminate a TCP connection. 

    If you are sending messages to an web serve then it should return the content-length header.  There's no guarantee.  As recommended above, do a GET for the image and read the response byte[] length.

    Otherwise, send an HTTP HEAD which returns the same HTTP header as a GET but without the content.  Below is a non-production working example.

    using (var client = new HttpClient())
    {
        HttpRequestMessage message = new HttpRequestMessage();
        message.Method = HttpMethod.Head;
        message.RequestUri = new Uri("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png");
        HttpResponseMessage response = await client.SendAsync(message);
    
        foreach(var h in response.Content.Headers)
        {
            Console.WriteLine($"{h.Key}: {h.Value.FirstOrDefault()}");
        }
    }
    Content-Type: image/png
    Content-Length: 13504
    Expires: Thu, 11 Jun 2020 16:42:39 GMT
    Last-Modified: Tue, 22 Oct 2019 18:30:00 GMT

    Thursday, June 11, 2020 4:43 PM
  • User-474980206 posted

    but then a HEAD may not return the length either. It is useful for static files, but when calling dynamic content, it often ends up running all the code, then throwing away the content.

    Thursday, June 11, 2020 5:51 PM