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;
}
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
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;
}
Cookiecontainer is not set some thing after send request via HttpWebRequest.
i use live httpheader chorme, and result after login
Set-Cookie: SHARINGSESSID4S=9jpuh21oi82s10mn6cvomjq190; expires=Mon, 29-Sep-2014 16:09:22 GMT;path=/; domain=.4share.v
however, i only get SHARINGSESSID4S=9jpuh21oi82s10mn6cvomjq190.
I cant use cookie for sub request.
my code:
private void button1_Click(object sender, EventArgs e)
{
CookieContainer cookie = new CookieContainer();
Uri site=new Uri("http://4share.vn/index/login");
var request = (HttpWebRequest)WebRequest.Create(site);
var postdata = "username=XXXXX&password=XXXXX";
var data = Encoding.ASCII.GetBytes(postdata);
request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
request.CookieContainer = cookie;
var stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
MessageBox.Show(cookie.GetCookieHeader(site));
var response = (HttpWebResponse)request.GetResponse();
MessageBox.Show(cookie.GetCookieHeader(site));
Uri site2 = new Uri("http://4share.vn/f/487b7d717a717b71/V-Z%20Naruto.Shippuden.Ultimate.Ninja.Storm.Revolution-CODEX#Jenty.VNZ.iso");
var request2 = (HttpWebRequest)WebRequest.Create(site2);
request2.CookieContainer = cookie;
var response2 = (HttpWebResponse)request2.GetResponse();
MessageBox.Show(cookie.GetCookieHeader(site2));
string Text = new StreamReader(response2.GetResponseStream()).ReadToEnd();
if (Text.IndexOf(" FileDownload: ") > 0) MessageBox.Show("success");
}
I have a picture that is presented in the form of a byte array. I need to save it to a file and send a post request. Tell me how to do it better
Here is what I do
private Stream file;
public void Fun1()
{
using (file = IsolatedStorageHelper.OpenFile(Picture, FileMode.Create))
{
file.Write(bt, 0, bt.Length);
_cookies = DataHolder.Instance.Cookies;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(String.Concat("http:// Mysite.com/image.php?image=FILE",file));
request.Method = "POST";
request.ContentType = "multipart/form-data";
request.CookieContainer = _cookies;
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackPlayersfun1), request);
}
}
private void GetRequestStreamCallbackPlayersfun1(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = request.EndGetRequestStream(asynchronousResult);
using (file = IsolatedStorageHelper.OpenFile(Picture, FileMode.Open))
{
BinaryReader br = new BinaryReader(file, Encoding.UTF8);
byte[] buffer = br.ReadBytes(2048);
while (buffer.Length > 0)
{
postStream.Write(buffer, 0, buffer.Length);
buffer = br.ReadBytes(2048);
}
}
postStream.Close();
request.BeginGetResponse(new AsyncCallback(ReadCallbackSavePlayersfun1), request);
}
private void ReadCallbackSavePlayersfun1(IAsyncResult asynchronousResult)
{
lock (__SYNC)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
}
}
As a result, the server did not come, tell me what am I doing wrong
thanks for your reply.
But I have another problem. My picture is encoded in a string, the string I write to the stream and try to send to the server. In response comes everything is OK, but the type of request is "Get"(variable respons, method ReadCallbackSavePlayersfun1). Please tell me what's wrong
public void Fun1()
{
string str = "iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAA";
using (file = IsolatedStorageHelper.OpenFile(Picture, FileMode.Create))
{
StreamWriter w = new StreamWriter(file,Encoding.UTF8);
w.WriteLine(str);
_cookies = DataHolder.Instance.Cookies;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(String.Concat("http://Mysite.com/image.php"));
string boundary = "----------" + DateTime.UtcNow.Ticks.ToString("x", CultureInfo.InvariantCulture);
request.Method = "POST";
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.CookieContainer = _cookies;
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackPlayersfun1), request);
w.Close();
}
}
private void GetRequestStreamCallbackPlayersfun1(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = request.EndGetRequestStream(asynchronousResult);
string boundary = "----------" + DateTime.UtcNow.Ticks.ToString("x", CultureInfo.InvariantCulture);
var sbHeader = new StringBuilder();
if (file != null)
{
sbHeader.AppendFormat("--{0}\r\n", boundary);
sbHeader.AppendFormat("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n", "picture", file);
sbHeader.AppendFormat("Content-Type: {0}\r\n\r\n", request.ContentType);
}
using (file = IsolatedStorageHelper.OpenFile(Picture, FileMode.Open))
{
byte[] header = Encoding.UTF8.GetBytes(sbHeader.ToString());
byte[] footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
long contentLength = header.Length + (file != null ? file.Length : 0) + footer.Length;
postStream.Write(header, 0, header.Length);
if (file != null)
{
BinaryReader br = new BinaryReader(file, Encoding.UTF8);
byte[] buffer = br.ReadBytes(2048);
while (buffer.Length > 0)
{
postStream.Write(buffer, 0, buffer.Length);
buffer = br.ReadBytes(2048);
}
br.Close();
}
postStream.Write(footer, 0, footer.Length);
postStream.Flush();
postStream.Close();
}
request.BeginGetResponse(new AsyncCallback(ReadCallbackSavePlayersfun1), request);
}
private void ReadCallbackSavePlayersfun1(IAsyncResult asynchronousResult)
{
lock (__SYNC)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
try
{
String doc = "";
using (Stream streamResponse = response.GetResponseStream())
{
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader readStream = new StreamReader(streamResponse, encode);
Char[] read = new Char[256];
int count = readStream.Read(read, 0, 256);
while (count > 0)
{
String str = new String(read, 0, count);
doc += str;
count = readStream.Read(read, 0, 256);
}
}
}
catch
{ }
}
}
Posting web byte[] data in .Net is not that simple. Saving a byte[] to storage is easy, so I wont have code for that, but here is the method I use to post binary data.
This is originally from http://skysanders.net/subtext/archive/2010/04/12/c-file-upload-with-form-fields-cookies-and-headers.aspx with my modifications to suit
And to get the FileInfo, simply pass in
new FileInfo(fullPath)
Good luck : )
/// <summary>
/// Create a new HttpWebRequest with the default properties for HTTP POSTS
/// </summary>
/// <param name="url">The URL to be posted to</param>
/// <param name="referer">The refer</param>
/// <param name="cookies">CookieContainer that should be used in this request</param>
/// <param name="postData">The post data</param>
private string CreateHttpWebUploadRequest(string url, string referer, CookieContainer cookies, NameValueCollection postData, FileInfo fileData, string fileContentType)
{
var request = (HttpWebRequest)HttpWebRequest.Create(url);
string boundary = "----------" + DateTime.UtcNow.Ticks.ToString("x", CultureInfo.InvariantCulture);
// set the request variables
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.CookieContainer = cookies;
request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.55 Safari/533.4";
request.Accept = "image/gif, image/jpeg, image/pjpeg, image/pjpeg, */*";
request.Headers.Add("Accept-Encoding: gzip,deflate");
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
request.Headers.Add("Accept-Language: en-us");
request.Referer = referer;
request.KeepAlive = true;
request.AllowAutoRedirect = false;
// process through the fields
var sbHeader = new StringBuilder();
// add form fields, if any
if (postData != null)
{
foreach (string key in postData.AllKeys)
{
string[] values = postData.GetValues(key);
if (values != null)
{
foreach (string value in values)
{
if (!string.IsNullOrEmpty(value))
sbHeader.AppendFormat("--{0}\r\n", boundary);
sbHeader.AppendFormat("Content-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}\r\n", key, value);
}
}
}
}
if (fileData != null)
{
sbHeader.AppendFormat("--{0}\r\n", boundary);
sbHeader.AppendFormat("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n", "media", fileData.Name);
sbHeader.AppendFormat("Content-Type: {0}\r\n\r\n", fileContentType);
}
byte[] header = Encoding.UTF8.GetBytes(sbHeader.ToString());
byte[] footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
long contentLength = header.Length + (fileData != null ? fileData.Length : 0) + footer.Length;
// set content length
request.ContentLength = contentLength;
// ref http://stackoverflow.com/questions/2859790/the-request-was-aborted-could-not-create-ssl-tls-secure-channel
// avoid The request was aborted: Could not create SSL/TLS secure channel exception
ServicePointManager.Expect100Continue = false;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(header, 0, header.Length);
// write the uploaded file
if (fileData != null)
{
// write the file data, if any
byte[] buffer = new Byte[fileData.Length];
var bytesRead = fileData.OpenRead().Read(buffer, 0, (int)(fileData.Length));
requestStream.Write(buffer, 0, bytesRead);
}
// write footer
requestStream.Write(footer, 0, footer.Length);
requestStream.Flush();
requestStream.Close();
using (var response = request.GetResponse() as HttpWebResponse)
using (var stIn = new System.IO.StreamReader(response.GetResponseStream()))
{
return stIn.ReadToEnd();
}
}
}