【问题标题】:API call using Auth to get image using HttpClient not working使用 Auth 的 API 调用使用 HttpClient 获取图像不起作用
【发布时间】:2017-07-12 14:59:04
【问题描述】:

我正在尝试使用 ASP.Net Core 中的 HttpClient 调用 API 来检索图像。问题是,它适用于常规图像(包含文件扩展名类型的图像),但不适用于我的 URL。

我不明白这是否与涉及凭据的 API URL 有关。

这是一个有效的调用:

HttpResponseMessage response = await client.GetAsync(
        "https://i.stack.imgur.com/hM8Ah.jpg?s=48&g=1");
byte[] content = await response.Content.ReadAsByteArrayAsync();
return "data:image/png;base64," + Convert.ToBase64String(content);

这是我的,没有:

HttpResponseMessage response = await client.GetAsync(
        "http://user:pass@CAMERA-IP/cgi-bin/snapshot.cgi?channel=0&authbasic=aXU8Hu1");
byte[] content = await response.Content.ReadAsByteArrayAsync();
return "data:image/png;base64," + Convert.ToBase64String(content);

有人遇到过这个问题吗?

有人知道为什么这不起作用吗?


这里是关于该 API 的更多信息:http://www.techprosecurity.com/

这是一个连接到某个位置的 IP 地址的摄像头系统,需要用户/通行证才能访问每个摄像头(通道)。

【问题讨论】:

  • 您能告诉我们更多关于该图像 API 的信息吗?
  • @Win 我继续编辑我的问题。
  • 你能通过浏览器获取该图像吗?您确定该网址具有http 方案吗?
  • 您收到什么错误信息?您确定它返回的图像是png而不是位图吗? authbasic=aXU8Hu1 是什么?
  • @IvanR。您可以 - 在某些浏览器中提供,提示您即将访问此页面的警报,通过单击“确定”您可以看到图像。是的http,不是https

标签: c# asp.net-core async-await httpclient


【解决方案1】:

我找到了一种解决方法,只需将授权嵌入标题中:

HttpClient client = new HttpClient();
var byteArray = Encoding.ASCII.GetBytes("username:password");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

HttpResponseMessage response = await client.GetAsync("http://CAMERA-IP/cgi-bin/snapshot.cgi?channel=0");
byte[] myBytes = await response.Content.ReadAsByteArrayAsync();
string convertedFromString = Convert.ToBase64String(myBytes);

return "data:image/png;base64," + convertedFromString;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多