post httpwebrequest to channel advisor - c#

I am trying to get new token from channeladvisor ecommerce
I am using this code
// HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.channeladvisor.com/oauth2/token");
var request=HttpWebRequest.Create("https://api.channeladvisor.com/oauth2/token");
WebResponse response = null;
string responseString = string.Empty;
try
{
// request.Timeout = 300000;
// request.KeepAlive = false;
//request.ContentType = "application/json";
request.UseDefaultCredentials = true;
string credentials = applicationid + ":" + sharesecret;
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(credentials);
string base64 = Convert.ToBase64String(bytes);
request.Headers["Authorization"] = "Basic " + base64;
request.ContentType = " application/x-www-form-urlencoded";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 |
SecurityProtocolType.Tls12;
request.Method = "Post";
// var stringContent = new StringContent("grant_type=refresh_token&refresh_token=" + refreshToken);
request.ContentLength = System.Text.Encoding.ASCII.GetByteCount("grant_type=refresh_token&refresh_token=" + refreshToken);
byte[] buffer = System.Text.Encoding.ASCII.GetBytes("grant_type=refresh_token&refresh_token=" + refreshToken);
// string result = System.Convert.ToBase64String(buffer);
Stream reqstr = request.GetRequestStream();
reqstr.Write(buffer, 0, buffer.Length);
reqstr.Close();
response = (HttpWebResponse)request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream);
responseString = reader.ReadToEnd();
}
}
catch (Exception)
{
throw;
}
but I keep getting the error
System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel.
what is problem? thank you

Try this Added this line:-
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
// Use SecurityProtocolType.Ssl3 if needed for compatibility reasons
Refer More From Here which help you alot

Related

Basic Authentication with multiple request header in HttpwebRequest in c#. Getting error 401 unauthorized

Getting 401 unauthorized error on calling external API from a console application.
through hhtpwebrequest class. Below is my code... requestBody gives me Json data to post
Please suggest to me how to do authentication.
public string InvokeRestService()
{
var serviceUrl = "http://xrmd0/api/v1.0/student/specialized/feed";
var reqData = _service.Retrieve("entityname",
new Guid("guid"), new ColumnSet("requestdata"));
var requestBody = reqData.Attributes["requestdata"].ToString();
string prefix = #"abc""";
string userName = prefix + "xyz";
string password = "pwdqawe";
try
{
var request = (HttpWebRequest)WebRequest.Create(new Uri(serviceUrl));
request.Method = "POST";
request.ContentType = "application/json";
request.Accept = "application/json";
//request.Headers["authorization"] = "Basic" + Convert.ToBase64String(Encoding.Default.GetBytes(userName + ":" + password));
request.Headers["Authorization"] = "Basic Auth" + Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(userName + ":" + password));
request.Headers["User-Id"] = "userId";
request.Headers["User-Type"] = "usertype";
if (!string.IsNullOrEmpty(requestBody))
{
byte[] data = Encoding.UTF8.GetBytes(requestBody);
var requestStream = request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
}
var response = (HttpWebResponse)request.GetResponse();
var responseStream = response.GetResponseStream();
var responseStreamReader = new StreamReader(responseStream, Encoding.UTF8);
var responseString = responseStreamReader.ReadToEnd();
responseStreamReader.Close();
return responseString;
}
catch (Exception ex)
{
}
}

Not receiving cookie suddenly for HttpWebRequest POST placed through Visual Studio C# code

There is a common framework in our company where we pass username, password, url and get the cookie back. It was working for me for a long time and suddenly it stopped working. My team mates are able to get the cookie successfully with no issues. Here is the common function that we use to get the cookie back. Please help me to complete the troubleshooting
public static CookieContainer GetAvidAuthCookies(string url, string userName, string password, bool allowAutoRedirect = false)
{
HttpWebRequest req = null;
HttpWebResponse resp = null;
CookieContainer cookieContainer = new CookieContainer();
req = (HttpWebRequest) WebRequest.Create(url);
req.CookieContainer = cookieContainer;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
// req.ContentType = "text/xml;charset=UTF-8"; //for SOAP
req.Timeout = 30000;
req.AllowAutoRedirect = allowAutoRedirect;
req.AllowWriteStreamBuffering = true;
req.Referer = url;
//req.Host = "api.avidxchange.net";
req.Headers["Authorization"] = "Basic " +
Convert.ToBase64String(
System.Text.Encoding.ASCII.GetBytes(userName + ":" + password));
var request = Common.GetMemoryStream("username=" + userName + "&password=" + password + "&submit=");
if (request != null)
{
req.ContentLength = request.Length;
Stream sw = req.GetRequestStream();
byte[] buffer = new byte[1024];
int bytesRead = 0;
request.Position = 0;
while ((bytesRead = request.Read(buffer, 0, buffer.Length)) != 0)
{
sw.Write(buffer, 0, bytesRead);
}
request.Flush();
request.Close();
sw.Flush();
sw.Close();
}
try
{
resp = (HttpWebResponse) req.GetResponse();
}
catch (WebException we)
{
resp = (HttpWebResponse) we.Response;
Debug.WriteLine("Response:" + we.InnerException + "\r\n" + resp.StatusCode + ":" +
new StreamReader(we.Response.GetResponseStream()).ReadToEnd());
var responseStream = we.Response.GetResponseStream();
if (responseStream != null) responseStream.Position = 0;
}
var rStream = resp.GetResponseStream();
var responseText = new StreamReader(rStream).ReadToEnd();
var t = resp.Cookies;
return cookieContainer;
}

308 permanent redirect with uploading PDF to REST API

I want to upload PDF to CrossEngage platform using HttpWebRequest or RestClient. As response I'm getting : 308 permanent redirect, but when i try this on POSTMAN all is fine (200 OK). What i'm not doing that POSTMAN is doing ?
//RestClient
byte[] dataBytes = System.IO.File.ReadAllBytes(path);
string converted = Convert.ToBase64String(dataBytes);
var client = new RestClient(Url+Action);
client.FollowRedirects = true;
var request = new RestRequest(Method.GET);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("x-xng-authtoken", AuthToken);
request.AddHeader("x-xng-apiversion", "2");
request.AddHeader("content-type", "application/pdf");
request.AddParameter("application/pdf", converted, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
return response.Content;
//HttpWebRequest
try
{
byte[] dataBytes = System.IO.File.ReadAllBytes(path);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + Action);
//request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.Headers.Add("X-XNG-ApiVersion", "2");
request.Headers.Add("X-XNG-AuthToken", AuthToken);
request.Method = method;
request.AllowAutoRedirect = true;
request.MaximumAutomaticRedirections = 1;
request.UseDefaultCredentials = false;
request.PreAuthenticate = true;
request.ContentLength = 0;
request.CookieContainer = new CookieContainer();
if (1 == 1)
{
request.ContentLength = dataBytes.Length;
request.ContentType = contentType;
using (Stream requestBody = request.GetRequestStream())
{
requestBody.Write(dataBytes, 0, dataBytes.Length);
}
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
catch (WebException webex)
{
string m = "";
using (HttpWebResponse response = (HttpWebResponse)webex.Response)
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
throw new Exception(reader.ReadToEnd());
}
}
I expect 200 OK status code
Thanks in advance
UPDATE: I have found a solution so it might help someone.
Simply you need to call location given in Location response header.
Hereby complete code :
try
{
byte[] dataBytes = System.IO.File.ReadAllBytes(path);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + Action);
//request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.Headers.Add("X-XNG-ApiVersion", "2");
request.Headers.Add("X-XNG-AuthToken", AuthToken);
request.Method = method;
request.AllowAutoRedirect = false;
if (1 == 1)
{
request.ContentLength = dataBytes.Length;
request.ContentType = contentType;
using (Stream requestBody = request.GetRequestStream())
{
requestBody.Write(dataBytes, 0, dataBytes.Length);
}
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if ((int)response.StatusCode >= 300 && (int)response.StatusCode <= 399)
{
var uriString = response.Headers["Location"];
var apiClient = (HttpWebRequest)WebRequest.Create(uriString);
apiClient.ContentType = contentType;
apiClient.Method = method;
apiClient.AllowAutoRedirect = false;
apiClient.Accept = "*/*";
apiClient.Headers.Add("X-XNG-ApiVersion", "2");
apiClient.Headers.Add("X-XNG-AuthToken", AuthToken);
apiClient.ContentLength = dataBytes.Length;
using (Stream requestBody = apiClient.GetRequestStream())
{
requestBody.Write(dataBytes, 0, dataBytes.Length);
}
var r = apiClient.GetResponse();
}
response.Close();
}
return "";
}
catch (WebException webex)
{
string m = "";
using (HttpWebResponse response = (HttpWebResponse)webex.Response)
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
throw new Exception(reader.ReadToEnd());
}
}

ALM Rest API : site-session returns 'The remote server returned an error: (400) Bad Request.'

I am getting '(400) Bad Request.' when I try complete authenticate against an ALM REST API, the first part (authentication) is successful) and I get the LWSSO_COOKIE_KEY, but site-session always fails with a 400 error code.
What am I doing wrong please... very confused!
// Authentication XML : 0 = User, 1 = Password
private const string AuthenticationXML = #"<alm-authentication>" +
"<user>{0}</user><password>{1}</password></alm-authentication>";
baseRequestURL = settings.QualityCentreURL + "/qcbin/";
Authentication is done first (and is successful) :
string authRequest = baseRequestURL + "authentication-point/alm-authenticate";
HttpWebRequest myauthrequest = (HttpWebRequest)WebRequest.Create(authRequest);
string xml = String.Format(AuthenticationXML, qcSettings.Username, qcSettings.Password);
byte[] Requestbytes = Encoding.UTF8.GetBytes(xml);
myauthrequest.Method = "POST";
myauthrequest.ContentType = "application/xml";
myauthrequest.ContentLength = Requestbytes.Length;
myauthrequest.Accept = "application/xml";
Stream RequestStr = myauthrequest.GetRequestStream();
RequestStr.Write(Requestbytes, 0, Requestbytes.Length);
RequestStr.Close();
HttpWebResponse myauthres = (HttpWebResponse)myauthrequest.GetResponse();
authenticationCookie = myauthres.Headers.Get("Set-Cookie");
The Site-Session code is :
public void GetSiteSession()
{
// Creat the web request fore site-session.
string request = baseRequestURL + "rest/site-session";
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(request);
string xml = String.Empty;
byte[] requestbytes = Encoding.UTF8.GetBytes(xml);
// Update the attributes before sending.
webRequest.Method = "POST";
webRequest.ContentType = "application/xml";
webRequest.Accept = "application/xml";
webRequest.Headers.Set(HttpRequestHeader.Cookie, authenticationCookie);
try
{
Stream requestStream = webRequest.GetRequestStream();
requestStream.Write(requestbytes, 0, requestbytes.Length);
requestStream.Close();
HttpWebResponse webRequestResponse = (HttpWebResponse)webRequest.GetResponse();
Stream responseStream = webRequestResponse.GetResponseStream();
XDocument doc = XDocument.Load(responseStream);
}
catch (System.Net.WebException except)
{
Console.WriteLine(except.Message);
}
}
I have tried cutting ;Path=/;HTTPOnly from LWSSO_COOKIE_KEY as per this question, but to no avail.
The API reference I found(here) seems to be a big vague or, possibly that I haven't understood it... :P
Apologies, it seems that with 12.53 I should have been using 'api/authentication/sign-in'
string requestURL = baseRequestURL + "api/authentication/sign-in";
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestURL);
var credentials = String.Format("{0}:{1}", qcSettings.Username, qcSettings.Password);
request.CookieContainer = authenticationCookieContainer;
request.Headers.Set(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials)));
var authResponse = request.GetResponse();
errorString = String.Empty;
}
catch (System.Net.WebException except)
{
errorString = except.Message;
return false;
}
errorString = String.Empty;
return true;
}

How To authenticate ALM from C# Windows Application Using Rest API

I am bit stuck here, trying to Integrate ALM using Rest API from C# Window application . But failed at the first step that is authentication .
Here is my Authentication call :
public void auth(string url, string xml)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
byte[] requestBytes = System.Text.Encoding.UTF8.GetBytes(xml.ToString());
req.Method = "POST";
req.ContentType = "application/xml";
req.Accept = "application/xml";
req.KeepAlive = true;
req.AllowAutoRedirect = true;
req.ContentLength = requestBytes.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(requestBytes, 0, requestBytes.Length);
requestStream.Close();
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream(), System.Text.Encoding.Default);
backstr = sr.ReadToEnd();
myheader = res.Headers.Get("Set-Cookie");
sr.Close();
res.Close();
}
which i am calling like this :
try
{
// my creds, server details
string server_ = #"https://MyAlmUrl";
string user_ = "username";
string password_ = "password";
string xmll = "<?xml version='1.0' encoding='utf-8'?><alm-authentication><user>" + user_ + "</user><password>" + password_ + "</password></alm-authentication>";
rest.auth(server_ + "/authentication-point/authenticate", xmll);
}
No matter what ever i do It lands into : 401 unauthorized error.
I do have a valid credentials as i am able to login using the web with same credentials .
Some one help me out, what i am doing wrong , As This ALM and using Rest API , both are new to me .
Try this :
HttpWebRequest myauthrequest = (HttpWebRequest)WebRequest.Create("http://{qcserver}/qcbin/authentication-point/alm-authenticate");
string AuthenticationXML = #"<alm-authentication>
<user>{qcserver-username}</user>
<password>{qcserver-pwd}</password>
</alm-authentication>";
byte[] Requestbytes = Encoding.UTF8.GetBytes(AuthenticationXML);
myauthrequest.Method = "POST";
myauthrequest.ContentType = "application/xml";
myauthrequest.ContentLength = Requestbytes.Length;
myauthrequest.Accept = "application/xml";
Stream RequestStr = myauthrequest.GetRequestStream();
RequestStr.Write(Requestbytes, 0, Requestbytes.Length);
RequestStr.Close();
HttpWebResponse myauthres = (HttpWebResponse)myauthrequest.GetResponse();
var AuthenticationCookie = myauthres.Headers.Get("Set-Cookie");
//request to get all domains in ALM
HttpWebRequest domainreq = (HttpWebRequest)WebRequest.Create("http://{qcserver}/qcbin/rest/domains/");
domainreq.Method = "GET";
domainreq.ContentType = "application/xml";
domainreq.Accept = "application/xml";
domainreq.Headers.Set(HttpRequestHeader.Cookie, AuthenticationCookie);
HttpWebResponse domainres= (HttpWebResponse)domainreq.GetResponse();
Stream RStream = domainres.GetResponseStream();
XDocument doc = XDocument.Load(RStream);
//request to dowmload a particular attachement assigned to a test case
HttpWebRequest attachmentreq = (HttpWebRequest)WebRequest.Create("http://{qcserver}/qcbin/rest/domains/{domainname}/project/{projectname}/tests/{testid}/attachments/file.xls");
attachmentreq.Method = "GET";
attachmentreq.ContentType = "application/xml";
attachmentreq.Accept = "application/octet-stream";
attachmentreq.Headers.Set(HttpRequestHeader.Cookie, AuthenticationCookie);
HttpWebResponse attachmentres= (HttpWebResponse)attachmentreq.GetResponse();
Stream RStream = attachmentres.GetResponseStream();
var fileStream = File.Create("C:\\PathToFile");
RStream.InputStream.CopyTo(fileStream);
fileStream.Close();

Categories