Ive a problem with a code because it work differently if I test it in Visual Studio either I test it on my site.
i am trying to do an autologin on an external web site. If I test it from VS, I am correctly redirected on the external site. From my site i obtain i am redirected to "http://www.MySite.com/cgi-bin/wbc_login/...."!!!!!
The code is the following:
private void MioMetodo(String username, String password)
{
CookieContainer Cookies = new CookieContainer();
Cookie langCookie = new Cookie("pk_lang", "\"italiano\"", "/");
langCookie.Domain = "xxx.yy";
Cookie loginCookie = new Cookie("wc_loginoslimit", "\"" + username + "\"", "/");
loginCookie.Domain = "xxx.yy";
Cookie passwordCookie = new Cookie("wc_passwordoslimit", "\"" + password + "\"", "/");
passwordCookie.Domain = "xxx.yy";
Cookies.Add(langCookie);
Cookies.Add(loginCookie);
Cookies.Add(passwordCookie);
UTF8Encoding encoding = new UTF8Encoding();
String postData = "wc_login=" + username + "&wc_password=" + password + "&limit=0&Avanti=Avanti";
Byte[] data = encoding.GetBytes(postData);
HttpWebRequest myHttpWebRequest = WebRequest.Create("http://xxx.yy/cgi-bin/wbc_login") as HttpWebRequest;
myHttpWebRequest.Method = "POST";
myHttpWebRequest.Referer = "http://xxx.yy/cgi-bin/wbc_login";
myHttpWebRequest.Headers.Add(HttpRequestHeader.AcceptCharset, "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
myHttpWebRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate,sdch");
myHttpWebRequest.Headers.Add(HttpRequestHeader.AcceptLanguage, "it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4");
myHttpWebRequest.Headers.Add(HttpRequestHeader.CacheControl, "max-age=0");
myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
myHttpWebRequest.CookieContainer = Cookies;
myHttpWebRequest.ContentLength = data.Length;
Stream newStream = myHttpWebRequest.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
HttpWebResponse myHttpWebResponse = myHttpWebRequest.GetResponse() as HttpWebResponse;
StreamReader streamRead =new StreamReader(myHttpWebResponse.GetResponseStream());
Response.Write(streamRead.ReadToEnd());
streamRead.Close();
myHttpWebResponse.Close();
}
Thanx in advance
Related
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 using ExtensionPackageUploader of ThingWorx to upload an extension through C#. It works when I run it from Visual Studio, but after installing it as a Windows service, it appears to not be working anymore.
public void UploadExtensionToThingWorx()
{
string endpoint = "/Thingworx/ExtensionPackageUploader";
string url = "http://" + serverAddress + ":" + serverPort + endpoint;
string filePath = Path.Combine(ExecutionDirectory, ExtensionFileName);
byte[] fileContent = ReadFile(filePath);
string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid());
string contentType = "multipart/form-data; boundary=" + formDataBoundary;
byte[] formData = GetMultipartFormData(formDataBoundary, ExtensionFileName, fileContent);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.ContentType = contentType;
request.CookieContainer = new CookieContainer();
request.ContentLength = formData.Length;
request.Headers.Add("AppKey", applicationKey);
request.Headers.Add("X-XSRF-TOKEN", "TWX-XSRF-TOKEN-VALUE");
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(formData, 0, formData.Length);
requestStream.Close();
}
}
Code is working when im running it directly from Visual studio.
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();
I am using the below code to post entries to Wufoo.com using the API. There is no error in the code and a new entry is being created under the correct form. The only problem is that the all the fields are blank for the new record. Can any please check this code and tell me what I am doing wrong here. Thanks for your help!!!!
string url = "https://cssoft.wufoo.com/api/v3/forms/registration-form/entries.json";
string postdata = "{\"Field1\":\"Anshuman\",\"Field3\":\"3216549870\":\"Field4\":\"test#new.com\"}";
byte[] byteArray = Encoding.UTF8.GetBytes(postdata);
WebRequest myReq = WebRequest.Create(url);
string username = "3QNW-MXE2-O74M-RUC6";
string password = "mfs802r0uokbfd";
string usernamePassword = username + ":" + password;
CredentialCache mycache = new CredentialCache();
mycache.Add(new Uri(url), "Basic", new NetworkCredential(username, password));
myReq.Credentials = mycache;
myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
myReq.ContentType = "multipart/form-data";
myReq.Method = "POST";
myReq.ContentLength = byteArray.Length;
Stream dataStream = myReq.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
Response.Write(content);
Try this code snippet this should work for you..
string url = "https://cssoft.wufoo.com/api/v3/forms/registration-form/entries.json";
string APIKey = "3QNW-MXE2-O74M-RUC6";
string Hashcode = "mfs802r0uokbfd";
string usernamePassword = APIKey + ":" + Hashcode;
// Prepare web request...
HttpWebRequest myReq =
(HttpWebRequest)WebRequest.Create(url);
CredentialCache mycache = new CredentialCache();
mycache.Add(new Uri(url), "Basic", new NetworkCredential(APIKey, Hashcode));
myReq.Credentials = mycache;
myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "Field1=Anshuman&Field3=3216549870&Field4=test#new.com";
byte[] data = encoding.GetBytes(postData);
myReq.Method = "POST";
myReq.ContentType = "application/x-www-form-urlencoded";
myReq.ContentLength = data.Length;
Stream newStream = myReq.GetRequestStream();
// Send the data.
newStream.Write(data, 0, data.Length);
newStream.Close();
Cheers!! This Would do your work what you are trying for..
I have a winforms application i have been working on that runs multiple tests on consumer accounts. The tests require a one time login in order to execute.
string paramaters = "authmethod=on&chkRememberMe=on&login-form-type=pwd&password=" + pw.Text + "&userid=" + uid.Text + "&username=" + uid.Text;
string strResponse;
HttpWebRequest requestLogin = (HttpWebRequest)WebRequest.Create("https://www.url.com/login.form");
requestLogin.Method = "POST";
requestLogin.CookieContainer = cookieJar;
requestLogin.ContentType = "application/x-www-form-urlencoded";
requestLogin.ContentLength = paramaters.Length;
StreamWriter stOut = new StreamWriter(requestLogin.GetRequestStream(), System.Text.Encoding.ASCII);
stOut.Write(paramaters);
stOut.Close();
StreamReader stIn = new StreamReader(requestLogin.GetResponse().GetResponseStream());
strResponse = stIn.ReadToEnd();
stIn.Close();
This script works for the login just fine, the problem is when i need to actually run the tests i need to return all the results into a string (HTML results).
private string runTestRequest(Uri url, string parameters)
{
string testResults = string.Empty;
HttpWebRequest runTest = (HttpWebRequest)WebRequest.Create(url);
runTest.CookieContainer = cookieJar;
runTest.Method = "POST";
runTest.ContentType = "application/x-www-form-urlencoded";
StreamWriter stOut = new StreamWriter(runTest.GetRequestStream(), System.Text.Encoding.ASCII);
stOut.Write(parameters);
stOut.Close();
StreamReader stIn = new StreamReader(runTest.GetResponse().GetResponseStream());
testResults = stIn.ReadToEnd();
stIn.Close();
return testResults;
}
But it goes and tries to login. How can i use the Cookie from the previous login request with this + many other web requests?
Thanks for the help.
EDIT:
I added this to my code yet which should do the same thing as BrokenGlass is saying except just a little different but still doesn't work.
foreach (Cookie cookie in responseLogin.Cookies)
{
cookieJar.Add(new Cookie(cookie.Name.Trim(), cookie.Value.Trim(), cookie.Path, cookie.Domain));
richTextBox2.Text += cookie.Name.ToString() + Environment.NewLine + cookie.Value.ToString() + Environment.NewLine + cookie.Path.ToString() + Environment.NewLine + cookie.Domain.ToString();
}
Something like this should work, I am using similar code to save a login cookie:
HttpWebRequest runTest;
//...do login request
//get cookies from response
CookieContainer myContainer = new CookieContainer();
for (int i = 0; i < Response.Cookies.Count; i++)
{
HttpCookie http_cookie = Request.Cookies[i];
Cookie cookie = new Cookie(http_cookie.Name, http_cookie.Value, http_cookie.Path);
myContainer.Add(new Uri(Request.Url.ToString()), cookie);
}
//later:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.url.com/foobar");
request.CookieContainer = myContainer;