C# 当服务器具有有效的 SSL 证书时,使用带有“https”的 WebClient.UploadFile() 时出现“握手失败...意外的数据包格式”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16895484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:04:45  来源:igfitidea点击:

Getting "Handshake failed...unexpected packet format" when using WebClient.UploadFile() with "https" when the server has a valid SSL certificate

c#visual-studio-2010httphttpswebclient

提问by user1867353

I am trying to use WebClient.UploadFile with a HTTPS URL but I am ending up with

我正在尝试将 WebClient.UploadFile 与 HTTPS URL 一起使用,但我最终得到了

"System.IO.IOException: The handshake failed due to an unexpected packet format"

“System.IO.IOException:由于意外的数据包格式,握手失败”

The same code works perfectly fine with Http but the server that I am trying to hit has a perfectly fine ssl certificate. Here is anything relevant to the web call:

相同的代码在 Http 上工作得很好,但我试图访问的服务器有一个非常好的 ssl 证书。以下是与网络电话相关的任何内容:

var url = WebServiceCommunication.GetProtocolName() + "..."; //turns out to be     "https://...
var wc = new WebClient();
//I am adding: 
wc.Headers.Add(HttpRequestHeader.KeepAlive, "...")
wc.Headers.Add(HttpRequestHeader.AcceptLanguage, "...")
we.Headers.Add(HttpRequestHeader.Cookie, "...")

wc.UploadFile(url, "POST", filename);

Is the issue with any of the HttpRequestHeaders I am adding AND using https with those? Or am I missing a necessary header if I want to use https? Does anyone have any pointers as to why this would work with HTTP but NOT HTTPS when the SSL cert is valid?

我添加并使用 https 的任何 HttpRequestHeaders 是否有问题?或者,如果我想使用 https,我是否缺少必要的标头?有没有人有任何关于为什么在 SSL 证书有效时这适用于 HTTP 而不适用于 HTTPS 的指示?

采纳答案by rene

You have to make sure the port you are connecting to is port 443 instead of port 80.

您必须确保您连接的端口是端口 443 而不是端口 80。

Example of explicitly setting the port to be used in the URL:

显式设置要在 URL 中使用的端口的示例:

var request = (HttpWebRequest) WebRequest.Create("https://example.com:443/");
request.Method = "GET";
request.UserAgent = "example/1.0";
request.Accept = "*/*";
request.Host = "example.com";

var resp = (HttpWebResponse) request.GetResponse();

回答by Brian Hasden

You can also get this error if you're clueless like me and don't recognize that your web server project has crashed and is no longer running.

如果您像我一样一无所知,并且没有意识到您的 Web 服务器项目已经崩溃并且不再运行,您也可能会收到此错误。