After authorisation on www.vkontakte.ru through ie8 me spans on page: www.vkontakte.ru/MyPage. But I cannot receive www.vkontakte.ru/MyPage through a code
HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(new Uri("http://vkontakte.ru/login.php", UriKind.Absolute));
authRequest.CookieContainer = new CookieContainer();
authRequest.AllowAutoRedirect = false;
string param = string.Format("email={0}&pass={1}&expire=1", HttpUtility.UrlEncode("---"), HttpUtility.UrlEncode("---"));
authRequest.Method = "POST";
authRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 3.5.30729)";
authRequest.ContentType = "application/x-www-form-urlencoded";
authRequest.ContentLength = param.Length;
authRequest.GetRequestStream().Write(Encoding.GetEncoding(1251).GetBytes(param), 0, param.Length);
HttpWebResponse authResponse = (HttpWebResponse)authRequest.GetResponse();
listBox1.Items.Add(authRequest.Address);
Returns http://vkontakte.ru/ instead of www.vkontakte.ru/MyPage =(
HttpContext.Current.Request.Url.AbsoluteUri - can help?
help me!
You forgot to close the request stream.
You should write the following:
using (Stream requestStream = authRequest.GetRequestStream())
using (StreamWriter writer = new StreamWriter(requestStream, Encoding.GetEncoding(1251))
writer.Write(param);
Also, you should run Fiddler check what the request and response look like.
Related
I would like to download an image from this url http://squirlytraffic.com/surficon.php?ts=1491591235
I tried this code but I don't see the image when I open it.
using (WebClient client = new WebClient())
{
client.DownloadFile("http://squirlytraffic.com/surficon.php?ts=1491591235", #"D:\image.jpg");
}
You need to set your credentials using the the WebClient Credentials property. You can do this by assigning it an instance of NetworkCredential. See below:
using (WebClient client = new WebClient()){
client.Credentials = new NetworkCredential("user-name", "password");
client.DownloadFile("url", #"file-location");
}
EDIT
If you don't want to hard code a username and password, you can set the UseDefaultCredentials property of the WebClient to true. This will use the credentials of the currently logged in user. From the documentation.
The Credentials property contains the authentication credentials used to access a resource on a host. In most client-side scenarios, you should use the DefaultCredentials, which are the credentials of the currently logged on user. To do this, set the UseDefaultCredentials property to true instead of setting this property.
Which would mean you could amend the above code to:
using (WebClient client = new WebClient()){
client.UseDefaultCredentials = true;
client.DownloadFile("url", #"file-location");
}
Try this way, those parameters are passed when login
StringBuilder postData = new StringBuilder();
postData.Append("login=" + HttpUtility.UrlEncode("username") + "&");
postData.Append("password=" + HttpUtility.UrlEncode("password") + "&");
postData.Append("Submit=" + HttpUtility.UrlEncode("Login"));
ASCIIEncoding ascii = new ASCIIEncoding();
byte[] postBytes = ascii.GetBytes(postData.ToString());
CookieContainer cc = new CookieContainer();
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create("http://squirlytraffic.com/members.php");
webReq.Method = "POST";
webReq.ContentType = "application/x-www-form-urlencoded";
webReq.ContentLength = postBytes.Length;
webReq.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
webReq.CookieContainer = cc;
Stream postStream = webReq.GetRequestStream();
postStream.Write(postBytes, 0, postBytes.Length);
postStream.Flush();
postStream.Close();
HttpWebResponse res = (HttpWebResponse)webReq.GetResponse();
HttpWebRequest ImgReq = (HttpWebRequest)WebRequest.Create("http://squirlytraffic.com/surficon.php?ts=1491591235");
ImgReq.Method = "GET";
ImgReq.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
ImgReq.CookieContainer = cc;
HttpWebResponse ImgRes = (HttpWebResponse)ImgReq.GetResponse();
Stream Img = ImgRes.GetResponseStream();
I am trying to write some code to connect to an HTTPS site that uses Siteminder authentication.
I keep getting a 401. Any ideas?
I have read a few different things on here but none have really seemed all that helpful. I am also using Fiddler/Firefox Tamper to snoop what's going on.
Here is what I've got so far in regards to code:
try
{
Uri uri = new Uri("https://websiteaddresshere");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri) as HttpWebRequest;
request.Accept = "text/html, application/xhtml+xml, */*";
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko";
// request.Connection = "Keep-Alive";
// request.Method = "Get";
// request.Accept = "text";
request.AllowAutoRedirect = true;
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
Cookie emersoncookie = new Cookie("SMCHALLENGE", "YES");
emersoncookie.Domain = "mydomain";
emersoncookie.Path = "/";
// authentication
var cache = new CredentialCache();
cache.Add(uri, "False", new NetworkCredential("myusername", "mypassword"));
request.Credentials = cache;
// response.
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
XmlTextReader reader = new XmlTextReader(stream);
MessageBox.Show(stream.ToString());
}
}
}
catch (WebException exception)
{
string responseText;
using (var reader = new StreamReader(exception.Response.GetResponseStream()))
{
responseText = reader.ReadToEnd();
MessageBox.Show(responseText.ToString());
}
}
After doing some more reading on the MSDN website I decided to go a different route.
I ended up making this a service since it will need to be a service at the end of the day and did the following:
CookieContainer emersoncookie = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create("https://websiteaddress");
request.Credentials = new NetworkCredential("username", "password");
request.CookieContainer = emersoncookie;
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)
request.GetResponse();
Stream resStream = response.GetResponseStream();
using (Stream output = File.OpenWrite(#"c:\\somefolder\\somefile.someextention"))
using (Stream input = resStream)
{
input.CopyTo(output);
}
To anyone that might be running into Siteminder authentication issues, this piece of code works pretty well.
I couldn't get Jasen's code to work. Maybe your SM setup is different from mine. But with SiteMinder it's generally a two step authentication process. The code block below works for me:
//Make initial request
RestClient client = new RestClient("http://theResourceDomain/myApp");
client.CookieContainer = new CookieContainer();
IRestResponse response = client.Get(new RestRequest("someProduct/orders"));
//Now add credentials.
client.Authenticator = new HttpBasicAuthenticator("username", "password");
//Get resource from the SiteMinder URI which will redirect to the correct API URI upon authentication.
response = client.Get(new RestRequest(response.ResponseUri));
Although this uses RestSharp, it can be easily replicated using HttpClient or even HttpWebRequest.
im trying to send POST request using HttpWebRequest and fiddler shows me that im sending GET?
any help will be appreciated since im able to see what im doing wrong.
code :
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(LOGIN_API_BASE_URL);
string postString = string.Format("api_email={0}&api_password={1}", EMAIL, PASSWORD);
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(postString);
CookieContainer cookies = new CookieContainer();
request.CookieContainer = cookies;
//request.AllowWriteStreamBuffering = true;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
request.Timeout = i_timeout;
//request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1";
//request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
//request.Referer = "https://accounts.craigslist.org";
using (Stream writer = request.GetRequestStream())
{
writer.Write(data, 0, data.Length);
//writer.Close();
}
StreamReader responseReader = new StreamReader(request.GetResponse().GetResponseStream());
string responseData = responseReader.ReadToEnd();
responseReader.Close();
request.GetResponse().Close();
ok found the problem, the url im sending the request to is http://domain.com and when i send it to http://www.domain.com it works and send a post. so new question why is that? ( the answer will get the answer to my question as i dont like the idea of voting my self )
I'm trying to login on facebook and retrive a token by using this link:
https://www.facebook.com/dialog/oauth?client_id=282892925078054&redirect_uri=https://www.facebook.com/&response_type=token
My code looks like this, but i get an invalid link when i'm requesting the link above.
CookieCollection cookies = new CookieCollection();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.facebook.com/login.php?login_attempt=1");
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
//Get the response from the server and save the cookies from the first request..
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
cookies = response.Cookies;
string getUrl = "https://www.facebook.com/login.php?login_attempt=1";
string postData = String.Format("email={0}&pass={1}", email, pass);
HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(getUrl);
getRequest.CookieContainer = new CookieContainer();
getRequest.CookieContainer.Add(cookies); //recover cookies First request
getRequest.Method = WebRequestMethods.Http.Post;
getRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
getRequest.AllowWriteStreamBuffering = true;
getRequest.ProtocolVersion = HttpVersion.Version11;
getRequest.AllowAutoRedirect = true;
getRequest.ContentType = "application/x-www-form-urlencoded";
byte[] byteArray = Encoding.ASCII.GetBytes(postData);
getRequest.ContentLength = byteArray.Length;
Stream newStream = getRequest.GetRequestStream(); //open connection
newStream.Write(byteArray, 0, byteArray.Length); // Send the data.
newStream.Close();
HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse();
cookies = getResponse.Cookies;
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
string sourceCode = sr.ReadToEnd();
}
//Get the token
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://www.facebook.com/dialog/oauth?client_id=282892925078054&redirect_uri=https://www.facebook.com/&response_type=token");
getRequest.CookieContainer = new CookieContainer();
getRequest.CookieContainer.Add(cookies);
webRequest.AllowAutoRedirect = false;
HttpWebResponse rresponse = (HttpWebResponse)webRequest.GetResponse();
if (rresponse.StatusCode == HttpStatusCode.Redirect)
{
Console.WriteLine("redirected to: " + rresponse.GetResponseHeader("Location"));
}
Please help me. Thanks in advance.
https://www.facebook.com/dialog/oauth?client_id=282892925078054&redirect_uri=https://www.facebook.com/&response_type=token
The URL does not allow the application configuration.: The application settings do not allow one or more of the URLs. Internet Site URL and Canvas URL or domain URLs must be sub-domains of application domains.
I have some code that logs me into Facebook and it works fine as far as returning me the page you see right after you log in.
But I'm trying to request my actual profile after I log in rather than just my news feed.
So I'd have to send my email and password to the login page, then request my profile.
How can I keep the login data around while requesting my profile?
Here is what I've got
public static string logIn()
{
//get the cookies before you try to log in
CookieCollection cookies = new CookieCollection();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.facebook.com");
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
cookies = response.Cookies;
response.Close();
//logging in
HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create("https://www.facebook.com/login.php?login_attempt=1");
getRequest.CookieContainer = new CookieContainer();
getRequest.CookieContainer.Add(cookies);
getRequest.Method = WebRequestMethods.Http.Post;
getRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
getRequest.AllowWriteStreamBuffering = true;
getRequest.ProtocolVersion = HttpVersion.Version11;
getRequest.AllowAutoRedirect = true;
getRequest.ContentType = "application/x-www-form-urlencoded";
//sending the email/password
byte[] byteArray = Encoding.ASCII.GetBytes("email=myemail#yahoo.com&pass=mypassword");
getRequest.ContentLength = byteArray.Length;
Stream newStream = getRequest.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);
newStream.Close();
//returns the source of the page after logging in
HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse();
StreamReader sr = new StreamReader(getResponse.GetResponseStream());
string source = sr.ReadToEnd();
cookies.Add(getResponse.Cookies);
//tries to get my profile source
//everything works fine until here
getRequest = (HttpWebRequest)WebRequest.Create("http://www.facebook.com/myprofile");
getRequest.CookieContainer = new CookieContainer();
getRequest.CookieContainer.Add(cookies);
getRequest.Method = WebRequestMethods.Http.Get;
getRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
getRequest.AllowWriteStreamBuffering = true;
getRequest.ProtocolVersion = HttpVersion.Version11;
getRequest.AllowAutoRedirect = true;
getRequest.ContentType = "application/x-www-form-urlencoded";
getResponse = (HttpWebResponse)getRequest.GetResponse();
sr = new StreamReader(getResponse.GetResponseStream());
source = sr.ReadToEnd();
getResponse.Close();
return source;
}
I've tried several ways of doing this and I have gotten it to return my profile, but it returns it as if I was not logged in and you can't actually view my profile (because it is set to private)
So I need my login info to be included somehow when requesting my profile.
This had me stumped for a while when I was making something similar. You need to make sure you're setting the proper cookies for your request after you've logged in. Try adding the new cookies to the CookieCollection object before applying them to your last request.
// ^ previous code ^
HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse();
StreamReader sr = new StreamReader(getResponse.GetResponseStream());
string source = sr.ReadToEnd();
Uri facebookPage = new Uri("http://www.facebook.com"); // .GetCookies() only accepts a Uri
cookies.Add(request.CookieContainer.GetCookies(facebookPage));
getResponse.Close(); // Always make sure you close your responses
// V requesting your profile code V
You have to start a CookieCollection at the beginning and use it for all requests.
A CookieCollection updates itself with new cookies whenever you do a request so using cookies.Add() was also messing it up.
But I got it working fine now.