I need to call HTTPS POST service from WEB API method.
I am using HttpWebRequest to call this API, however i am getting error as
"A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond x.x.x.x:443"
When I tried to call this API in Windows Form then it works well.
HttpWebRequest r = null;
HttpWebResponse rsp = null;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
r = (HttpWebRequest)System.Net.WebRequest.Create("url");
String d = "Serialize JSON"
r.Method = "POST";
r.ContentType = "application/json";
StreamWriter wr = new StreamWriter(r.GetRequestStream());
wr.WriteLine(d);
wr.Close();
rsp = (HttpWebResponse)r.GetResponse();
StreamReader reader = new StreamReader(rsp.GetResponseStream());
String dd = reader.ReadToEnd();
Might be because you are trying to use SSL, from the last part - x.x.x.x:443. My understanding is that 443 is used for SSL. Happy for someone to correct me if I incorrect.
Have a look at the following, this may help you out:
https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/working-with-ssl-in-web-api
Related
I am having an issue :
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond URL.
Also I get issue like:
System.IO.IOException: Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host
and
System.Net.WebException: The operation has timed out at System.Net.WebClient.UploadFile(Uri address, String method, String fileName)
I know that this question has asked before but believe me I tried almost every single resolution at my end.
Weird thing is this issue does not appear at my end at all and only when client try to use which is not constant. Some time my application works fine at their end too.
What I am trying to accomplish is I have created an desktop application (Win Forms & C#) and trying to login client while sending request to my php api server which is hosted on GODaddy.
var request = (HttpWebRequest)WebRequest.Create("url");
if (request != null)
{
#region System.Net.WebException
request.Method = "POST";
if (!string.IsNullOrEmpty(body))
{
var requestBody = Encoding.UTF8.GetBytes(body);
request.ContentLength = requestBody.Length;
request.ContentType = "application/json";
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(requestBody, 0, requestBody.Length);
}
}
else
{
request.ContentLength = 0;
}
request.Timeout = 15000;
request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
string output = string.Empty;
try
{
using (var response = (HttpWebResponse)request.GetResponse())
{
using (var stream = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(1252)))
{
if (response.StatusCode == HttpStatusCode.OK)
{
while (!stream.EndOfStream)
{
output += stream.ReadLine();
}
output = stream.ReadToEnd();
}
}
}
}
catch
{
// Excaption Caught here
}
}
Please help me out.
Thanks in advance.
Try adding this...
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.ServicePoint.ConnectionLimit = 12;
MSDN article recommends 12 connections per CPU hence the limit of 12 because it's hosted by GoDaddy so I'm sure the server resources are limited.
I think I got the answer. Thought to post it so that it could help anyone else.
It most probably the particular machine issue or server issue but in my case, I tried to set Request.proxy = null and it worked like a charm.
I faced this problem at today. I set Timeout property of HttpWebRequest to 1 200 000 milliseconds (20 minute), but I got this error after 5 minute. I researched many sites at google and I found ReadWriteTimeout property of HttpWebRequest. Default value of ReadWriteTimeout is 5 minute. I increased value of ReadWriteTimeout and problem solved for me.
...
httpWebRequest.Timeout = 1200000;
httpWebRequest.ReadWriteTimeout = 1200000;
...
I realise there have been a number of similar posts to this but I haven't found a solution yet. Am trying to post some xml to an MPI gateway but keep getting the following error:
Unable to read data from the transport connection: An existing
connection was forcibly closed by the remote host.
Below is the code I'm currently using but have tried just about every different approach I can think of and they all return the same error:
string result = "";
string xml = "<TNSAuthRequest><CardNumber>0123456789</CardNumber><ExpiryDate>1801</ExpiryDate><PurchaseAmt>750</PurchaseAmt><CurrencyCode>826</CurrencyCode><CurrencyExponent>2</CurrencyExponent><CountryCode>826</CountryCode><MerchantName>Mayflower</MerchantName><MerchantId>0123456789</MerchantId><MerchantData>abcdefghijklmnopqrstuvwxyz0123456789</MerchantData><MerchantUrl>example.com</MerchantUrl><NotificationURL>example.com/basket</NotificationURL></TNSAuthRequest>";
var url = "https://mpi.securecxl.com";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes("xmldata=" + xml.ToString());
ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(ValidateRemoteCertificate);
var req = (HttpWebRequest)WebRequest.Create(url);
req.AllowWriteStreamBuffering = true;
req.ContentType = "text/xml";
req.Method = "POST";
//req.ContentLength = bytes.Length;
req.KeepAlive = false;
req.ProtocolVersion = HttpVersion.Version10;
req.ServicePoint.ConnectionLimit = 1;
//req.Timeout = -1;
try
{
using (var writer = new StreamWriter(req.GetRequestStream(), Encoding.ASCII))
{
writer.WriteLine(bytes);
}
using (WebResponse resp = req.GetResponse())
{
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
result = sr.ReadToEnd().Trim();
}
}
}
catch (Exception ex)
{
result = ex.Message + "<br />" + ex.InnerException.Message + "<br /><br />" + xml.Replace("<", "<");
}
ViewBag.result = result;
Am basically wandering if anyone can see anything that might be wrong with the code that could be causing this error or if it's most likely I problem on the their end? Have tried running on my localhost, our live server and my own private server (with a completely different IP) and still get same result.
Any ideas?
I think its because you are connecting to "https" url. In this case you have to add following line to your code.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
It will accept "ssl" protocol for your request. "ServicePointManager.ServerCertificateValidationCallback" handler just controls certificate validity.
Slightly better perhaps:
System.Net.ServicePointManager.SecurityProtocol = System.Net.ServicePointManager.SecurityProtocol | System.Net.SecurityProtocolType.Tls12;
#AlisettarHuseynli is right, this sometimes has to do with https. Most likely occurs when the infrastructure gets updates which may mean TLS gets updated for example from TLS1.0 to TLS1.2 Usually happens with some APIs, etcetera.
If the service you are trying to access can be accessed over http, do that. Change the scheme from https to http. Worked in my case. Otherwise you'll have to add code to support higher versions of TLS. Popular software usually have an opt-in option to use TLS1.2 instead of the old TLS1.0.
The following code for simple secure-ftp fails on my Windows 7 computer but succeeds on a Server 2012 computer on a different network: If I remove the EnableSsl = true it works fine.
public static string TheContent(string url, string username, string password)
{
ServicePointManager.ServerCertificateValidationCallback = OnValidateCertificate;//returns true.
string result = "";
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
request.Timeout = 7000;
request.EnableSsl = true;
request.UsePassive = true;
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential(username, password);
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
result = reader.ReadToEnd();
return result;
}
I've tried many things. Some of them:
Disabling the firewall. (Though I'm using passive mode)
Setting port forwarding on my router.
Using "active".
Using FileZilla (fails the same way)
Connecting to the modem by cable
Much longer timeout
And more.
I always get an exception at (FtpWebResponse)request.GetResponse()
"Unable to read data from the transport connection: A connection
attempt failed because the connected party did not properly respond
after a period of time, or established connection failed because
connected host has failed to respond."
When using Microsoft Network Monitor 3.4 I see that the error seems to be:
FTP:Response to Port , '234 AUTH command ok. Expecting
TLS Negotiation.'
FTP:Response to Port , '451 The parameter is incorrect.
'
Any ideas? Can it be that the non-server Windows aren't capable for this by default and something has to be enabled first?
I have tried to integrate paypal sandbox with my project in asp.net.
Redirection to paypal sandbox working extremely fine ! You can check out your cart ! You can make payment ! But the problem is when paypal set redirection to my Success.aspx page !
I got the error as
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 192.168.0.101:808
I am using stream writer Object !
Wait Let me post my code !
this is page_load even of Success.aspx
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Used parts from https://www.paypaltech.com/PDTGen/
// Visit above URL to auto-generate PDT script
authToken = WebConfigurationManager.AppSettings["PDTToken"];
//read in txn token from querystring
txToken = Request.QueryString.Get("tx");
query = string.Format("cmd=_notify-synch&tx={0}&at={1}", txToken, authToken);
// Create the request back
string url = WebConfigurationManager.AppSettings["PayPalSubmitUrl"];
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
// Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = query.Length;
// Write the request back IPN strings
StreamWriter stOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
stOut.Write(query);
stOut.Close();
// Do the request to PayPal and get the response
StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream());
strResponse = stIn.ReadToEnd();
stIn.Close();
// sanity check
Label2.Text = strResponse;
// If response was SUCCESS, parse response string and output details
if (strResponse.StartsWith("SUCCESS"))
{
PDTHolder pdt = PDTHolder.Parse(strResponse);
Label1.Text = string.Format("Thank you {0} {1} [{2}] for your payment of {3} {4}!",
pdt.PayerFirstName, pdt.PayerLastName, pdt.PayerEmail, pdt.GrossTotal, pdt.Currency);
}
else
{
Label1.Text = "Oooops, something went wrong...";
}
}
}
This sentence creates error !!
StreamWriter stOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
These type of exception occurs
Exception Details: System.Net.Sockets.SocketException:
A connection attempt failed because the connected party did
not properly respond after a period of time,
or established connection failed because connected
host has failed to respond 192.168.0.101:808
First off, do not mix PDT and IPN - just use IPN. Go into PayPal admin and make sure that the return URL is NOT set there and that PDT is NOT enabled.
There is an IPN class available online just for this purpose - some more info (Caveat: my own blog post):
http://codersbarn.com/?tag=/paypal
http://paypalipnclass.codeplex.com/releases/view/31282
I am not able to use Webrequest in a windows service. It fails with error ""Unable to connect to the remote server".
WebRequest request = WebRequest.Create(url);
NetworkCredential nc = new NetworkCredential("myuname","mypassword","mydomain");
request.Proxy.Credentials = nc;
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
}
catch (WebException ex)
{
//ex.Message is "Unable to connect to the remote server"
}
The code works perfectly fine if it is a console application.
Could someone please tell if there is a fix?
You might want to try specifying the proxy server on the request object you've created. When you run the console application I believe that the system looks up your IE configuration for you and the proxy may be set. If the service is running under an account other than yours it might not have the proxy set.
I was facing the same problem. After lots of R&D a solution worked for me.
Instead of:
WebResponse responseObject = requestObject.GetResponse();
I wrote:
WebResponse responseObject = null;
responseObject = requestObject.GetResponse();
and it worked fine.
I am also looking for the exact reason behind this behavior.