检查uri是否有效,而不会使用HttpClient下载它

时间:2017-05-18 21:12:34

标签: c# httpclient

如何验证下载uri是否有效而不会导致客户端下载内容?

1 个答案:

答案 0 :(得分:-2)

  1. 创建客户端
  2. 使用client.GetAsync(uri,HttpComplettionOption)api
  3. 使用ResponseHeadersRead
  4. 这只会检查uri是否有效而不下载实际内容。

    HttpClient client = new HttpClient();
    var downloadUri = new Uri("https://domainame/someblobcontent.zip");
    Task<HttpResponseMessage> response = null;
    try
     {
           using (response = client.GetAsync(downloadUri, HttpCompletionOption.ResponseHeadersRead))
                {
                    if(response.Result.IsSuccessStatusCode)
                    {
                        Console.WriteLine("uri is valid, got response code {0}", response.Result.StatusCode);
                    }
                    else
                    {
                        Console.WriteLine("uri is not valid, got response code {0}", response.Result.StatusCode);
                    }
                }
      }
      catch(Exception e)
      {
          Console.WriteLine(e.ToString());
      }