如何使用web客户端访问安全url

本文关键字:安全 url 访问 客户端 何使用 web | 更新日期: 2023-09-27 18:02:23

我试图通过web客户端访问安全的url,并得到一些错误。总的目的是从安全的url下载图像..

请注意,早些时候,我能够使用http从存储库下载图像,现在他们在同一url中强制执行(安全)https。我们有一个控制台应用程序,它定期运行,从服务器提取图像并存储在本地。

请告诉我我做错了什么?或者缺少什么?

以下是我所面临的问题。

  1. ///如果我使用代码节1…我得到错误说参数无效。
  2. ///如果我使用代码节2…文件被保存到本地,但得到一个消息"文件似乎损坏或大,无法打开。

第1节和第2节列在下面。

            using (WebClient webClient = new WebClient())
            {
                webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
                webClient.Credentials = new NetworkCredential("id", "pwd");  // if credentials are wrong...still I get the imageByte
                /// section 1 - if I use this code... I get error saying Parameter is not valid.
                // ----------------------------- Start --------------------------------
                imageByte = webClient.DownloadData("https://someurl/source/abcd.jpeg");
                ////Initialize image variable
                Image newImage;
                ////Read image data into a memory stream
                using (MemoryStream ms = new MemoryStream(imageByte, 0, imageByte.Length, true))
                {
                    ms.Write(imageByte, 0, imageByte.Length);
                    //Set image variable value using memory stream.
                    newImage = Image.FromStream(ms, true, false); // Throws error at this line saying that parameter is not valid.
                }
                newImage.Save(@"location'image.jpeg");
                // ----------------------------- End --------------------------------

                /// section 2 - if I use this code... File gets saved to local but get a message " File appear to be corrupt or large and not able to open.
                // ----------------------------- Start --------------------------------
                webClient.DownloadFile("https://someurl/source/abcd.jpeg", @"location'image.jpeg");
                // ----------------------------- End --------------------------------
            } 

如何使用web客户端访问安全url

这两个错误都表示下载的数据不是有效的JPEG图像。可能是因为服务器返回了一些错误。

为了检查服务器是否返回了一个错误,你可以看看HTTP响应头和正文中的内容。

  • 对于正文,您可以尝试使用文本编辑器打开第2节保存的文件。

  • 对于标头,您可以检查webClient。

下面的例子取自MSDN:

// Obtain the WebHeaderCollection instance containing the header name/value pair from the response.
WebHeaderCollection myWebHeaderCollection = myWebClient.ResponseHeaders;
Console.WriteLine("'nDisplaying the response headers'n");
// Loop through the ResponseHeaders and display the header name/value pairs.
for (int i=0; i < myWebHeaderCollection.Count; i++)
{       
    Console.WriteLine ("'t" + myWebHeaderCollection.GetKey(i) + " = " + myWebHeaderCollection.Get(i));
}

查看从服务器实际返回的内容的另一种方法是调用- webrequest PowerShell cmdlet或wget实用程序(两者都应该支持HTTPS和身份验证)

你的代码运行良好。正如Kel建议的那样,最可能的服务器响应头给出可能给出一个答案。您确定服务器已配置为支持https吗?

不需要提供网络凭据。因为HTTPS只是一个传输协议。它只保护连接。

要进行身份验证,您必须配置服务器,例如进行BASIC或DIGEST身份验证。如果需要,设置对所请求资源的授权。

关于你的代码的一个注释:不要忘记处理newImage.