I have a WSDL generated from Tibco, the WSDL can be imported and run under SoapUI and I can connect without any issue with HTTPS even without Certificate however tried connecting to the same Endpoint using c# I can not connect with the following Code:
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.KeepAlive = true;
req.Accept = "gzip,deflate";
req.Headers.Add("SOAPAction", soapActionHeader);
req.ContentType = "text/xml;charset=UTF-8";
req.Method = "POST";
req.Timeout = requestTimeOut;
#endregion
#region Adding XML body to request
Stream strm = null;
using (var streamWriter = new StreamWriter(req.GetRequestStream()))
{
streamWriter.Write(xmlSOAPTemplate);
streamWriter.Flush();
streamWriter.Close();
}
#endregion
#region HTTP RESPONSE
string resultValue = string.Empty;
WebResponse resp = req.GetResponse();
strm = resp.GetResponseStream();
StreamReader streamReader = new StreamReader(strm);
string res = streamReader.ReadToEnd();
ExceptionHandler.WriteLog($"{url}:Response:{res}", MethodBase.GetCurrentMethod().Name);
XmlSerializer serializer = new XmlSerializer(typeof(T));
result = (T)serializer.Deserialize(strm);
So, How can we solve this issue?
what is the error you're getting ?
Your code seems to manipulate pure HTTP API, while you should use a library that invoke SOAP over HTTP.
I'm no C# programmer, but I googled the subject and found this example (see step 7) :
https://www.c-sharpcorner.com/UploadFile/88b6e5/how-to-call-web-service-in-android-using-soap/
SOAP can be fairly complex (and especially if you use TIBCO Business Works to produce it with an entreprise project behind), calling it with HTTP API will be complicated.
Related
In C # application, when calling API interface, it often takes 15+ seconds to access. API is deployed in another network segment of intranet and needs to be accessed by proxy. Some one said that it was a DNS problem, try to setting the host, which has no effect.
Environment: Windows Server 2012 R2, IIS v8.5
Code Script:
private string PostHttp(string url, string authHeader, string requestBody)
{
var webRequest = System.Net.WebRequest.Create(url);
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
byte[] data = System.Text.Encoding.UTF8.GetBytes(requestBody);
webRequest.Method = "POST";
webRequest.Headers.Add("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
webRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
webRequest.Headers.Add("Authorization", authHeader);
webRequest.ContentLength = data.Length;
webRequest.ContentType = "application/x-www-form-urlencoded";
System.Net.WebProxy proxy = new System.Net.WebProxy("http://myHttpProxyAddress", false);
proxy.Credentials = new System.Net.NetworkCredential("HttpProxyUser", "HttpProxyPassword");
webRequest.Proxy = proxy;
var writer = webRequest.GetRequestStream();
writer.Write(data, 0, data.Length);
writer.Close();
using (WebResponse webResponse = webRequest.GetResponse())
{
System.IO.StreamReader reader = null;
if (webResponse.Headers["Content-Encoding"] == "gzip")
reader = new System.IO.StreamReader(new GZipStream(webResponse.GetResponseStream(), CompressionMode.Decompress), System.Text.Encoding.UTF8);
else
reader = new System.IO.StreamReader(webResponse.GetResponseStream(), System.Text.Encoding.UTF8);
var result = reader.ReadToEnd();
reader.Close();
return result;
}
}
it's very difficult to point out by just hearing someone said one of the possibility (e.g DNS error) , try to use some http utility (e.g Curl) to check and measure that.
you can wrap the request above with below this guide and measure the timing detail.
How do I measure request and response times at once using cURL?
I created a c# console application to log into a website with Selenium and it works great. Now I want to add this feature to an existing .Net Core application.
So far I have the following:
string formUrl = "https://cap.mcmaster.ca/mcauth/login.jsp?app_id=1505&app_name=Avenue";
string formParams = string.Format("user_id={0}&pin={1}", "user", "pass"); //In my program I have the correct credentials
string cookieHeader;
var cookies = new CookieContainer();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(formUrl);
req.CookieContainer = cookies;
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
cookieHeader = resp.Headers["Set-cookie"];
string pageSource;
string getUrl = "https://avenue.cllmcmaster.ca/d2l/home";
HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(getUrl);
getRequest.CookieContainer = new CookieContainer();
getRequest.CookieContainer.Add(resp.cookies);
getRequest.Headers.Add("Cookie", cookieHeader);
getRequest.Headers.Add("Cookie", cookieHeader);
WebResponse getResponse = getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
For some reason, in the above code Cookies is underlined in "resp.Cookies" as an error. (CS1061 'WebResponse' does not contain a definition for 'Cookies' and no accessible extension method 'Cookies' accepting a first argument of type 'WebResponse' could be found)
I tried to folow the posts here: Login to website, via C# but I can't seem to get it to work.
The reason you are getting a compile time error is because the WebResponse class does not have a Cookies property.
From .NET Docs
The WebResponse class is the abstract base class from which
protocol-specific response classes are derived.
Instead, take a look at the HttpWebResponse class. This class provides a HTTP specific implementation of WebResponse.
You can cast the WebResponse to a HttpWebResponse:
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
HttpWebResponse.Cookies Property
Gets or sets the cookies that are associated with this response.
Documentation
HttpWebResponse.Cookies
In my web project, I am using http request and response for access https payment site. But when I call getresponse() function, it return "Precondition failed (412)" error.
HttpWebRequest paymentRequest = (HttpWebRequest)WebRequest.Create("https://xxxxxx/authorize");
Uri uri = new Uri("https://xxxxxx/authorize");
NetworkCredential netCredential = new NetworkCredential("XXXXXXXXX", "XXXXXXXXX");
paymentRequest.Credentials = netCredential.GetCredential(uri, "Basic");
paymentRequest.PreAuthenticate = true;
byte[] Data = System.Text.Encoding.ASCII.GetBytes(sXMLTemplate);
paymentRequest.Method = "POST";
paymentRequest.Headers.Add("MIME-Version", "1.0");
paymentRequest.Headers.Add("Request-number", "1");
paymentRequest.Headers.Add("Document-type", "Request");
paymentRequest.Headers.Add("Content-transfer-encoding", "application/xml");
paymentRequest.ContentType = "application/xml";
paymentRequest.ContentLength = Data.Length;
paymentRequest.KeepAlive = true;
Stream streamWriter = paymentRequest.GetRequestStream();
streamWriter.Write(Data, 0, Data.Length);
streamWriter.Close();
HttpWebResponse paymentResponse = (HttpWebResponse)paymentRequest.GetResponse();
Stream responseStream = paymentResponse.GetResponseStream();
reader = new XmlTextReader(responseStream);
How to fix this error?
Please check if XML data you are POSTing validates successfully and there is no missing XML elements if XML schema is enforced
Have a look at the valid content-transfer-encodings.
BASE64
8BIT
7BIT
BINARY
QUOTED-PRINTABLE
application/something is for Content-Type, not encoding.
For more info, look at the specs here:
http://www.w3.org/Protocols/rfc1341/5_Content-Transfer-Encoding.html
What I do Think you're after is this:
paymentRequest.Headers.Add("Content-type", "application/xml");
or simply:
paymentRequest.ContentType = "application/xml";
may i know is there any foursquare sdk for .NET C#.
I am doing based on the developer reference but i failed to do it during request for token, i keep on getting the error.
I am using VS 2008 and under development server. I search before this error because of url rewriting, but i'm not hosted in IIS and i also have check the web.config, no luck also. Please help, thanks.
This is my error:
The HTTP verb POST used to access path '/login' is not allowed.
This is my implementation:
HttpWebRequest request = null;
HttpWebResponse response = null;
StreamReader responseStream = null;
ASCIIEncoding ascii = null;
string key = ConfigurationManager.AppSettings["key"];
string secret = ConfigurationManager.AppSettings["secret"];
string callback = ConfigurationManager.AppSettings["callback"];
string obtainTokenUrl = ConfigurationManager.AppSettings["obtainTokenUrl"];
try
{
string postData = "client_id=" + key + "&response_type=code&redirect_uri=" + callback;
ascii = new ASCIIEncoding();
byte[] postBytes = ascii.GetBytes(postData);
try
{
request = WebRequest.Create(obtainTokenUrl) as HttpWebRequest;
}
catch (UriFormatException)
{
request = null;
}
if (request == null)
{
throw new ApplicationException("Invalid URL: " + obtainTokenUrl);
}
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;
//add post data to request
Stream postStream = request.GetRequestStream();
postStream.Write(postBytes, 0, postBytes.Length);
postStream.Close();
response = (HttpWebResponse)request.GetResponse();
Encoding encode = Encoding.GetEncoding("utf-8");
responseStream = new StreamReader(response.GetResponseStream(), encode);
Response.Write(responseStream.ReadToEnd());
Well, this may be a roundabout sort of answer. But maybe you could check out the open source 4square app for windows phone 7:
http://4square.codeplex.com/
Since you can look at the source code, you can see how they are interfacing with the 4sq API :-)
SharpSquare - FourSquare SDK for .NET http://www.igloolab.com/sharpsquare/
How do I consume a RESTful web service in C# code without wcf? Something very simple
Use the WebRequest class. See A REST Client Library for .NET, Part 1.
Please use the below code to invoke a RESTful web service.
string responseMessage;
HttpClient client = new HttpClient(serviceUrl);
HttpWebRequest request = WebRequest.Create(string.Concat(serviceUrl, resourceUrl)) as HttpWebRequest;
request.ContentType = "text/xml";
request.Method = method;
HttpContent objContent = HttpContentExtensions.CreateDataContract(requestBody);
if(method == "POST" && requestBody != null)
{
//byte[] requestBodyBytes = ToByteArrayUsingXmlSer(requestBody, "http://schemas.datacontract.org/2004/07/XMLService");
byte[] requestBodyBytes = ToByteArrayUsingDataContractSer(requestBody);
request.ContentLength = requestBodyBytes.Length;
using (Stream postStream = request.GetRequestStream())
postStream.Write(requestBodyBytes, 0, requestBodyBytes.Length);
//request.Timeout = 60000;
}
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if(response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
responseMessage = reader.ReadToEnd();
}
else
{
responseMessage = response.StatusDescription;
}
The above code needs to refer the following namespaces:
using Microsoft.Http; --> Available from the REST Starter Kit (Microsoft.Http.dll)
using System.Net;
using System.IO;
Look at the OpenRasta project - it is a REST Architecture Solution Targeting Asp.net.