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

 我有一個功能去採集別人網站有用的內容,採集內容中有一個圖片連接,能夠單獨打開,但放在個人網站就沒法顯示,出錯提示:async

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

在個人網站加一箇中轉請求,在服務端獲取圖片流,輸出到個人客戶端(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(重點),部分代碼實現:url

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地址由spa

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

改爲cdn

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

圖片就能顯示了圖片

相關文章
相關標籤/搜索