C# HttpWebRequest The underlying connection was closed: An unexpected error occurred on a send -


i'm hoping can me this. i've been googling morning , trying solutions find or think of myself. site i'm trying load running tls1.2 few other sites tried test make sure wasn't tls1.2 issue. other sites loaded fine.

byte[] buffer = encoding.ascii.getbytes(     "mod=www&ssl=1&dest=account_settings.ws"     + "&username=" + username.replace(" ", "20%")     + "&password=" + password.replace(" ", "20%"));  servicepointmanager.maxservicepointidletime = 1000; servicepointmanager.securityprotocol = securityprotocoltype.tls;  httpwebrequest webreq =     (httpwebrequest)webrequest.create(         "https://secure.runescape.com/m=weblogin/login.ws");  webreq.method = "post"; webreq.keepalive = false;  webreq.referer =     "https://secure.runescape.com/m=weblogin/loginform.ws"     + "?mod=www&ssl=1&expired=0&dest=account_settings.ws";  webreq.contenttype = "application/x-www-form-urlencoded"; webreq.contentlength = buffer.length; stream postdata = webreq.getrequeststream(); postdata.write(buffer, 0, buffer.length); postdata.close(); httpwebresponse webresp = (httpwebresponse)webreq.getresponse(); stream answer = webresp.getresponsestream(); streamreader _answer = new streamreader(answer); reply = _answer.readtoend(); curaccount++; if (reply.contains("login successful")) {      eturn true; } else {      eturn false; } 

no matter try keep getting exception

the underlying connection closed: unexpected error occurred on send.

under more details found

authentication failed because remote party has closed transport stream.

in 4.0 version of .net framework servicepointmanager.securityprotocol offered two options set:

  • ssl3: secure socket layer (ssl) 3.0 security protocol.
  • tls: transport layer security (tls) 1.0 security protocol

in next release of framework securityprotocoltype enumerator got extended newer tls protocols, if application can use th 4.5 version can use:

  • tsl11: specifies transport layer security (tls) 1.1 security protocol
  • tsl12: specifies transport layer security (tls) 1.2 security protocol.

so if on .net 4.5 change line

servicepointmanager.securityprotocol = securityprotocoltype.tls; 

to

servicepointmanager.securityprotocol = securityprotocoltype.tls12; 

so servicepointmanager create streams support tls12 connections.

do notice enumeration values can used flags can combine multiple protocols logical or

servicepointmanager.securityprotocol = securityprotocoltype.tls |                                         securityprotocoltype.tls11 |                                        securityprotocoltype.tls12; 

Comments