HttpWebRequest возвращает ошибку «Базовое соединение было закрыто» - PullRequest
0 голосов
/ 29 ноября 2018

Мне просто нужно позвонить на веб-страницу и получить ответную страницу.Я использую следующий код для вызова веб-страницы.Этот код работал отлично в течение нескольких месяцев.Однако совсем недавно строка, которая вызывает GetResponse, теперь возвращает ошибку «Базовое соединение было закрыто».Я приложил подробные журналы System.Net, но не могу понять, что не так.Если я изменю URL-адрес на http://microsoft.com, ответ будет работать нормально.Похоже, это связано с конкретным сайтом, на который я звоню.Я пробовал много разных URL-адресов на gocomics.com (например, https, нет www и т. Д.), Но ничего не получилось.Когда я просматриваю логи, я не могу определить причину сбоя GetResponse.

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri("http://www.gocomics.com"));

// Set some reasonable limits on resources used by this request
request.MaximumAutomaticRedirections = 4;
request.MaximumResponseHeadersLength = 4;

// Set credentials to use for this request.
request.Credentials = CredentialCache.DefaultCredentials;

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Я также пытался просто использовать этот простой код, но все еще не удалось

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri("http://www.gocomics.com"));
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

ВотВ журнале System.Net установлено подробное

System.Net Verbose: 0 : [51100] Entering 

WebRequest::Create(http://www.gocomics.com/)
System.Net Verbose: 0 : [51100] Entering HttpWebRequest#54986669::HttpWebRequest(http://www.gocomics.com/#1880366986)
System.Net Information: 0 : [51100] Current OS installation type is 'Client'.
System.Net Information: 0 : [51100] RAS supported: True
System.Net Verbose: 0 : [51100] Exiting HttpWebRequest#54986669::HttpWebRequest()
System.Net Verbose: 0 : [51100] Exiting WebRequest::Create()    -> HttpWebRequest#54986669
System.Net Verbose: 0 : [51100] Entering HttpWebRequest#54986669::GetResponse()
System.Net Error: 0 : [51100] Can't retrieve proxy settings for Uri 'http://www.gocomics.com/'. Error code: 12180.
System.Net Verbose: 0 : [51100] Entering ServicePoint#23686174::ServicePoint(www.gocomics.com:80)
System.Net Information: 0 : [51100] Associating HttpWebRequest#54986669 with ServicePoint#23686174
System.Net Information: 0 : [51100] Associating Connection#31609076 with HttpWebRequest#54986669
System.Net Information: 0 : [51100] Connection#31609076 - Created connection from 10.0.0.208:13441 to 66.6.101.183:80.
System.Net Information: 0 : [51100] Associating HttpWebRequest#54986669 with ConnectStream#20903718
System.Net Information: 0 : [51100] HttpWebRequest#54986669 - Request: GET / HTTP/1.1

System.Net Information: 0 : [51100] ConnectStream#20903718 - Sending headers
{
Host: www.gocomics.com
Connection: Keep-Alive
}.
System.Net Information: 0 : [51100] Connection#31609076 - Received status line: Version=1.1, StatusCode=301, StatusDescription=Moved Permanently.
System.Net Information: 0 : [51100] Connection#31609076 - Received headers
{
Connection: Close
Content-Length: 0
Content-Type: text/html
Location: https://www.gocomics.com/
}.
System.Net Information: 0 : [51100] ConnectStream#51746094::ConnectStream(Buffered 0 bytes.)
System.Net Information: 0 : [51100] Associating HttpWebRequest#54986669 with ConnectStream#51746094
System.Net Information: 0 : [51100] Associating HttpWebRequest#54986669 with HttpWebResponse#41215084
System.Net Warning: 0 : [51100] HttpWebRequest#54986669::() - Error code 301 was received from server response.
System.Net Warning: 0 : [51100] HttpWebRequest#54986669::() - Resubmitting request.
System.Net Verbose: 0 : [51100] Entering ServicePoint#12096874::ServicePoint(www.gocomics.com:443)
System.Net Information: 0 : [51100] Associating HttpWebRequest#54986669 with ServicePoint#12096874
System.Net Information: 0 : [51100] Associating Connection#26209817 with HttpWebRequest#54986669
System.Net Information: 0 : [51100] Connection#26209817 - Created connection from 10.0.0.208:13443 to 66.6.101.183:443.
System.Net Information: 0 : [51100] TlsStream#860689::.ctor(host=www.gocomics.com, #certs=0, checkCertificateRevocationList=False, sslProtocols=Default)
System.Net Information: 0 : [51100] Associating HttpWebRequest#54986669 with ConnectStream#35288276
System.Net Information: 0 : [51100] HttpWebRequest#54986669 - Request: GET / HTTP/1.1

System.Net Information: 0 : [51100] ConnectStream#35288276 - Sending headers
{
Host: www.gocomics.com
Connection: Keep-Alive
}.
System.Net Information: 0 : [51100] SecureChannel#37533195::.ctor(hostname=www.gocomics.com, #clientCertificates=0, encryptionPolicy=RequireEncryption)
System.Net Information: 0 : [51100] Enumerating security packages:
System.Net Information: 0 : [51100]     Negotiate
System.Net Information: 0 : [51100]     NegoExtender
System.Net Information: 0 : [51100]     Kerberos
System.Net Information: 0 : [51100]     NTLM
System.Net Information: 0 : [51100]     TSSSP
System.Net Information: 0 : [51100]     pku2u
System.Net Information: 0 : [51100]     WDigest
System.Net Information: 0 : [51100]     Schannel
System.Net Information: 0 : [51100]     Microsoft Unified Security Protocol Provider
System.Net Information: 0 : [51100]     Default TLS SSP
System.Net Information: 0 : [51100]     CREDSSP
System.Net Information: 0 : [51100] SecureChannel#37533195 - Left with 0 client certificates to choose from.
System.Net Information: 0 : [51100] SecureChannel#37533195::.AcquireClientCredentials, new SecureCredential() (flags=(ValidateManual, NoDefaultCred, SendAuxRecord), m_ProtocolFlags=(Ssl3Client, Tls10Client), m_EncryptionPolicy=RequireEncryption)
System.Net Information: 0 : [51100] AcquireCredentialsHandle(package = Microsoft Unified Security Protocol Provider, intent  = Outbound, scc     = System.Net.SecureCredential)
System.Net Information: 0 : [51100] InitializeSecurityContext(credential = System.Net.SafeFreeCredential_SECURITY, context = (null), targetName = www.gocomics.com, inFlags = ReplayDetect, SequenceDetect, Confidentiality, AllocateMemory, InitManualCredValidation)
System.Net Information: 0 : [51100] InitializeSecurityContext(In-Buffer length=0, Out-Buffer length=120, returned code=ContinueNeeded).
System.Net Error: 0 : [51100] Exception in HttpWebRequest#54986669:: - The underlying connection was closed: An unexpected error occurred on a send..
System.Net Information: 0 : [51100] Associating HttpWebRequest#54986669 with ServicePoint#12096874
System.Net Information: 0 : [51100] Associating Connection#62465990 with HttpWebRequest#54986669
System.Net Information: 0 : [51100] Connection#62465990 - Created connection from 10.0.0.208:13444 to 66.6.101.183:443.
System.Net Information: 0 : [51100] TlsStream#10968766::.ctor(host=www.gocomics.com, #certs=0, checkCertificateRevocationList=False, sslProtocols=Default)
System.Net Information: 0 : [51100] Associating HttpWebRequest#54986669 with ConnectStream#47066262
System.Net Information: 0 : [51100] HttpWebRequest#54986669 - Request: GET / HTTP/1.1

System.Net Information: 0 : [51100] ConnectStream#47066262 - Sending headers
{
Host: www.gocomics.com
Connection: Keep-Alive
}.
System.Net Information: 0 : [51100] SecureChannel#50668565::.ctor(hostname=www.gocomics.com, #clientCertificates=0, encryptionPolicy=RequireEncryption)
System.Net Information: 0 : [51100] SecureChannel#50668565 - Left with 0 client certificates to choose from.
System.Net Information: 0 : [51100] Using the cached credential handle.
System.Net Information: 0 : [51100] InitializeSecurityContext(credential = System.Net.SafeFreeCredential_SECURITY, context = (null), targetName = www.gocomics.com, inFlags = ReplayDetect, SequenceDetect, Confidentiality, AllocateMemory, InitManualCredValidation)
System.Net Information: 0 : [51100] InitializeSecurityContext(In-Buffer length=0, Out-Buffer length=120, returned code=ContinueNeeded).
System.Net Error: 0 : [51100] Exception in HttpWebRequest#54986669:: - The underlying connection was closed: An unexpected error occurred on a send..
System.Net Error: 0 : [51100] Exception in HttpWebRequest#54986669::GetResponse - The underlying connection was closed: An unexpected error occurred on a send..

Ответы [ 2 ]

0 голосов
/ 29 ноября 2018

В соответствии с возможными решениями -

  1. Вы можете попытаться использовать разные или несколько протоколов безопасности:

SecurityProtocolTypes: SecurityProtocolType.Ssl3, SecurityProtocolType.Tls, SecurityProtocolType.Tls11

Поскольку этот код работал раньше, это может быть проблемой на стороне сервера, когда они отключили поддержку TLS1.0

Установите HttpWebRequest.KeepAlive в False

0 голосов
/ 29 ноября 2018

Сайт перенаправляется на HTTPS, и вы явно указали ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12.Возможно, сайт не поддерживает эту версию протокола и закрывает соединение.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...