1. 程式人生 > >通過服務端中轉顯示防盜鏈圖片

通過服務端中轉顯示防盜鏈圖片

pub 獲取圖片 agen pad gen int handler handle pic

我有一個功能去采集別人網站有用的內容,采集內容中有一個圖片鏈接,可以單獨打開,但放在我的網站就無法顯示,出錯提示:

技術分享圖片

很明顯,有防盜鏈功能,只能在他的網站才能打開,這個好辦,幾行代碼

在我的網站加一個中轉請求,在服務端獲取圖片流,輸出到我的客戶端(localhost):

// GET: Home/PickUpImage?src=http://xxxx:yy
public async Task<ActionResult> PickUpImage(string src)
{
    if (string.IsNullOrEmpty(src)) return HttpNotFound();
    
var stream = await HttpHelper.GetAsync(src); return File(stream, "image/png"); }

其中 HttpHelper 是我操作HTTP請求的工具類(必須是單例模式或靜態方法類,不能做成實例類) ,裏面是通過 HttpClient 實現的,每次請求都會記住Cookie(重點),部分代碼實現:

public class HttpHelper
    {
        private static readonly HttpClient _hc;
        static HttpHelper()
        {
            _hc 
= new HttpClient(new HttpClientHandler { AllowAutoRedirect = false, UseCookies = true }); _hc.MaxResponseContentBufferSize = 2 * 1024 * 1024; //2MB _hc.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36
"); _hc.Timeout = new TimeSpan(0, 1, 0); //1 minute } public static async Task<Stream> GetAsync(string url) { if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); } return await Client.GetStreamAsync(url); } }

這樣頁面上img的src地址由

https://cdn.whatismyipaddress.com/images/flags/mo.png

改成

http://localhost:3721/Home/PickUpImage?src=https://cdn.whatismyipaddress.com/images/flags/mo.png

圖片就能顯示了

通過服務端中轉顯示防盜鏈圖片