HttpWebRequest Post synchronous call - TimeOut not working - c#

My webrequest timeout does not seem to be working. The URL that host has some TLS setting issue. But even in cases of exceptions, is it not expected to respect the timeout?
The hostname has the domain name and not IP.Please let me know what I am missing for the timeout to work at 30secs immaterial of success/exception scenarios.
Find the code below - we have currently kept the timeout to be 30s but recieving the response after 1.15mins or more.
public string CallJsonService(string JsonString, string ServiceURL, string strLogUser, string RandomValue, string strAPIToCall)
{
string displayvalue = "";
try
{
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) => { return true; };
ServicePointManager.Expect100Continue = false;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;
byte[] bytestream = Encoding.UTF8.GetBytes(JsonString);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(ServiceURL);
req.Method = "POST";
req.ContentType = "application/json; charset=utf-8";
req.ContentLength = bytestream.LongLength;
req.Timeout = 30000;
req.ReadWriteTimeout = 30000;
req.KeepAlive = true;
String ProxyValue = objCommon.GetParamValue("ProxyValueForInstant");
req.Proxy = new System.Net.WebProxy(ProxyValue, true);
req.Headers.Add("vRanKey", Convert.ToString(RandomValue));
req.Accept = "application/json";
using (Stream stream = req.GetRequestStream())
{
stream.Write(bytestream, 0, bytestream.Length);
stream.Flush();
}
using (WebResponse responserequest = req.GetResponse())
{
Stream ResponseStream = responserequest.GetResponseStream();
displayvalue = HttpUtility.HtmlDecode((new StreamReader(ResponseStream)).ReadToEnd());
}
}
catch (WebException e)
{
using (WebResponse response = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
if (response != null)
{
using (Stream data = response.GetResponseStream())
{
using (var reader = new StreamReader(data))
{
displayvalue = reader.ReadToEnd();
}
}
}
else
{
throw e;
}
}
}
catch (Exception ex)
{
throw ex;
}
return displayvalue;
}

Related

Making a web request with SSL Certificate and SOAP on C#

I am facing an issue while making a request to an external web service from a C# code with SSL certificate authentication. Currently I am getting error code 500 Internal Server Error from that web service as response.
C# code to make request object and call it:
public class ERCOTWebRequest
{
string action = #"https://testmisapi.ercot.com/2007-08/Nodal/eEDS/EWS?MarketInfo";
public bool GetReports()
{
try
{
// WebRequestHelper.
var request = CreateSOAPWebRequest();
XmlDocument SOAPReqBody = new XmlDocument();
//SOAP Body Request
string nodalXml = File.ReadAllText(#"C:\Users\test\source\repos\WebRequestHelper\ERCOTWebServiceHelper\XMLFile1.xml");
SOAPReqBody.LoadXml(nodalXml);
using (Stream stream = request.GetRequestStream())
{
SOAPReqBody.Save(stream);
}
//Geting response from request
using (WebResponse Serviceres = request.GetResponse())
{
using (StreamReader rd = new StreamReader(Serviceres.GetResponseStream()))
{
//reading stream
var ServiceResult = rd.ReadToEnd();
//writting stream result on console
Console.WriteLine(ServiceResult);
Console.ReadLine();
}
}
return true;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
public HttpWebRequest CreateSOAPWebRequest()
{
string host = #"https://testmisapi.ercot.com/2007-08/Nodal/eEDS/EWS/";
string certName = #"C:\Users\Test\Downloads\ERCOT_TEST_CA\TestAPI123.pfx";
string password = #"password";
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
X509Certificate2Collection certificates = new X509Certificate2Collection();
certificates.Import(certName, password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);
ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => true;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(host);
req.AllowAutoRedirect = true;
req.ClientCertificates = certificates;
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Headers.Add("SOAPAction", action);
req.Proxy = WebRequest.GetSystemWebProxy();
//HTTP method
req.Method = "POST";
return req;
}
}
Currently I am getting an error(Error 500: Internal Server error) while trying to make SOAP request. Someone please help.

How to fix Remote name could not be resolved in C# HTTP Request;

I recently switched my backend-server to https and going into production I deployed it on a AWS EC2, but my windows-client refuses to communicate with the server, and gives me an exception with the message:
"Remote name could not be resolved"
Here's a sample code
public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificatecertification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
return true;
}
var request = (HttpWebRequest) WebRequest.Create("https://api.mybackend.com/login");
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
var data = Encoding.ASCII.GetBytes(User.Login());
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
try
{
var response = (HttpWebResponse) request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
if (responseString != null)
{
return GrailsController.Instance.User.Parse(responseString);
}
}
catch (Exception e)
{
return false;
}
The exception occurs on var response = (HttpWebResponse) request.GetResponse(); and for the love of god I can't find a solution to this problem.

I am trying to write a console app in c# that consume a web service running on tomcat, to perform a "PUT" method with an xml file

public static String TransferMessage(String uri, String resource,
String xml_data, Method httpmethod,
ReturnType returnType)
{
try
{
WebRequest request = WebRequest.Create(uri + resource);
request.Method = httpmethod.ToString();
request.ContentType = #"application/xml;";
//request.Headers.Add("Token", token);
request.Timeout = Convert.ToInt32((new TimeSpan(1, 0, 0)).TotalMilliseconds);
request.ContentLength = Encoding.UTF8.GetByteCount(xml_data);
if (httpmethod != Method.GET)
using (Stream stream = request.GetRequestStream())
{
stream.Write(Encoding.UTF8.GetBytes(xml_data), 0,
Encoding.UTF8.GetByteCount(xml_data));
stream.Flush();
stream.Close();
}
return getResponseContent(request.GetResponse());
}
catch(Exception e)
{
Console.WriteLine(e);
}
return null;
}
Main method:
var res_xml = MethodHelper.TransferMessage(endpoint, "/" + resource,xml,
MethodHelper.Method.PUT,
MethodHelper.ReturnType.XML);
I am getting this error
ERROR javax.xml.bind.UnmarshalException\n - with
linked exception:\n[org.xml.sax.SAXParseException; line Number: 1;
columnNumber: 1; Content is not allowed in prolog.]
try{
string contend = "";
using (var streamReader = new StreamReader(new FileInfo(#"C:\Users\absmbez\Desktop\temp\upload.xml").OpenRead()))
{
contend = streamReader.ReadToEnd();
}
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
webrequest.Method = "PUT";
webrequest.ContentType = "application/xml";
Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
byte[] requestData = enc.GetBytes(contend);
webrequest.ContentLength = requestData.Length;
using (var stream = webrequest.GetRequestStream())
{
stream.Write(requestData, 0, requestData.Length);
}
HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
StreamReader responseStream = new StreamReader(webresponse.GetResponseStream(), enc);
string result = string.Empty;
result = responseStream.ReadToEnd();
webresponse.Close();
return result;
}
catch (Exception e)
{
Console.WriteLine(e);
}

Bad Request when updating api in HttpWebRequest

I have used Cin 7 Endpoints to Update Order. Here is the link: Cin7 Update Order
and then when calling a api I will have Bad Request error. Here is the code
public string UpdateData(string endpoint, Dispatched saleOrder)
{
string xmlStringResult = string.Empty;
try
{
var req = (HttpWebRequest)WebRequest.Create(endpoint);
req.Method = "PUT";
req.ContentType = "application/json";
req.Credentials = GetCredential(endpoint);
var json = JsonConvert.SerializeObject(saleOrder);
if (!String.IsNullOrEmpty(json))
{
using (var ms = new MemoryStream())
{
using (var writer = new StreamWriter(req.GetRequestStream()))
{
writer.Write(json);
writer.Close();
}
}
}
using (var resp = (HttpWebResponse)req.GetResponse())
{
return resp.StatusDescription + resp.StatusCode;
}
}
catch (Exception ex)
{
AppendError(string.Format("UpdateData catch exception: {0}", ex.Message), LogType.System);
}
return xmlStringResult;
}
Extracting credential
private CredentialCache GetCredential(string url)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var credentialCache = new CredentialCache();
credentialCache.Add(new Uri(url), "Basic", new NetworkCredential(_cred.Username, _cred.Key));
return credentialCache;
}
Here is the json data to update
{"id":2631912,"dispatchedDate":"2018-05-10T11:49:41.6238207+08:00","trackingCode":"6J7010926112","reference":"255552"}
Please help and thank you in advance.

Web Service dynamically using HttpWebRequest Unsupported Media Type

public void processVoucher()
{
try
{
string url = "http://192.168.xxx.xx:xxxx/context-root-xxxxxxxx/AccountsPayableManagerPort?WSDL/processVoucher";
StreamReader str = new StreamReader(#"F:\IntelliChief integration to JD Edwards for AP Invoice entry\processVoucher_input_payload.xml");
string ipParameter = str.ReadToEnd();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.ContentType = "application/xml";
req.KeepAlive = true;
req.Timeout = 30000;
req.Accept = "application/xml";//"text/xml";
req.Headers.Clear();
req.Method = "POST";
Encoding encode = Encoding.GetEncoding("utf-8");
using (Stream stm = req.GetRequestStream())
{
using (StreamWriter stmw = new StreamWriter(stm))
{
stmw.Write(ipParameter);
}
}
var response = req.GetResponse(); // here i am getting Unsupported Media Type issue
Stream responseStream = response.GetResponseStream();
StreamReader strReader = new StreamReader(responseStream, encode, true);
string result = strReader.ReadToEnd();
}
catch (Exception ex)
{
MessageBox.Show("Error Message:" + ex.Message);
throw;
}
}
I got requirement of consuming web service, display the result, i am trying to consume web service by using HttpWebRequest class. I running exception in req.GetResponse() any help is appreciated.
public void processVoucher()
{
string soap = null;
try
{
StreamReader str = new StreamReader(#"F:\xxx\some.xml");
soap = str.ReadToEnd();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://192.168.xxx.xx:xxxx/bla-bla-bla/AccountsPayableManagerPort?WSDL");
req.ContentType = "text/xml;charset=\"UTF-8\"";
req.Accept = "text/xml";
req.Method = "POST";
using (Stream stm = req.GetRequestStream())
{
using (StreamWriter stmw = new StreamWriter(stm))
{
stmw.Write(soap);
}
}
using (WebResponse response = req.GetResponse())
{
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
string soapResult = rd.ReadToEnd();
}
}
}
catch (Exception)
{
throw;
}
}
Finally i found solution to the issue, above is the working code. After i changed req.ContentType = "application/xml"; to req.ContentType = "text/xml;charset=\"UTF-8\""; , req.Accept = "application/xml"; to req.Accept = "text/xml"; and i removed req.Headers.Clear(); my code started working thanks all for your support...

Categories

Resources