c# Winform picturebox 从 url 加载图像出现 403 错误

问题描述 投票:0回答:1

我尝试通过URL将在线图像加载到winform应用程序的图片框中,但它返回403错误,代码如下:


private void MainFunction()
{
    string PictureURL = getURLFromSomeWhere();

    if (PictureURL != string.Empty || PictureURL != null)
    {
        LoadPicture(pictureBox1, PictureURL);
    }
}


private void LoadPicture(System.Windows.Forms.PictureBox LoadBox, string LoadPath) 
{
    WebRequest request = WebRequest.Create(LoadPath);
    WebResponse response = request.GetResponse();
    Stream stream = response.GetResponseStream();
    LoadBox.Image = System.Drawing.Bitmap.FromStream(stream);
}

我收到的错误消息: 远程服务器返回错误:(403) Forbidden。

我尝试了 PictureBox.load() 但不起作用...

c# winforms picturebox http-status-code-403
1个回答
0
投票

ChatGPT 解决了我的问题...

它需要一个 User-Agent 标头,并且最好使用异步来防止程序在下载图像时冻结。

这是代码:

private async void LoadSignature(System.Windows.Forms.PictureBox LoadBox, string LoadPath)
{
    try
    {
        //use HttpClient instead of WebRequest
        using (System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient())
        {
            //User-Agent Header
            httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36");
            byte[] imageData = await httpClient.GetByteArrayAsync(LoadPath);

            // Create a MemoryStream to hold the image data
            using (var stream = new System.IO.MemoryStream(imageData))
            {
                // Create a new Bitmap from the stream
                Bitmap bitmap = new Bitmap(stream);
                LoadBox.Image = bitmap;
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error loading image: " + ex.Message);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.