google-drive-api - 验证不允许 HEAD 时 URL 中是否存在图像
问题描述
在 C# 中使用HttpClient
时,我试图在不下载实际图像的情况下验证图像是否存在于给定的 URL 中。这些图像可以来自任何可公开访问的地址。我一直在使用HEAD
似乎适用于许多/大多数的 HTTP 动词。谷歌驱动器图像被证明是困难的。
给定一个像这样的公共共享链接:
https://drive.google.com/file/d/1oCmOEJp0vk73uYhzDTr2QJeKZOkyIm6v/view?usp=sharing
我可以愉快地使用HEAD
, 得到 a200 OK
并且它似乎很高兴。但是,这不是图像。这是一个可以下载图像的页面。
稍微麻烦一下,您可以将 URL 更改为此以实际获取图像,这是我真正想要检查的内容:
https://drive.google.com/uc?export=download&id=1oCmOEJp0vk73uYhzDTr2QJeKZOkyIm6v
但是,如果HEAD
该405 MethodNotAllowed
URL 确实不存在,您会返回一个404 NotFound
所以我被困在405
. HEAD
在不允许的情况下,我的下一步是什么(不使用 Google API) ?如果它根本不是,我不能假设它是一个有效的图像404
。我检查Content-type
以验证它是一个图像,该图像存在此问题范围之外的问题。
解决方案
HttpClient
允许我们发出一个 http 请求,您可以在其中指定您只对标头感兴趣。
诀窍是将HttpCompletionOption
枚举值传递给 theSendAsync
或任何其他{HttpVerb}Async
方法:
| Enum name | Value | Description |
|---------------------|-------|---------------------------------------------------------------------------------------------------------------------|
| ResponseContentRead | 0 | The operation should complete after reading the entire response including the content. |
| ResponseHeadersRead | 1 | The operation should complete as soon as a response is available and headers are read. The content is not read yet. |
await client.GetAsync(targetUrlWhichDoesNotSupportHead, HttpCompletionOption.ResponseHeadersRead);
这是一篇深入的文章,详细介绍了此枚举如何更改HttpClient
.
相关源码片段:
- 如果是.NET Framework
- 如果是.NET Core
推荐阅读
- opengl - 片段着色器忽略纹理坐标
- python-3.x - 如何使用for循环计算字典中的键数
- reactjs - On which level should I start/stop writing tests?
- image - 是否可以从 Firebase 静态托管服务图像?
- python - 如何从txt文件中提取字符串(数字)并在python中使用正则表达式转换为整数
- c# - 如何使用 C# 在 Aspose.word 中获取自定义目录
- vue.js - Vue Router 无法使用 jest 从内部单元测试中导航
- r - 如何按条件和按组过滤我的 data.table?
- python - 如何将具有范围值的列添加到 DataFrame
- r - 我在哪里可以找到有关 ggplot2 中“..count..”和“..group..”特殊变量的信息?