Search Results

Search found 180 results on 8 pages for 'httpwebresponse'.

Page 3/8 | < Previous Page | 1 2 3 4 5 6 7 8  | Next Page >

  • Logging Into a site that uses Live.com authentication with C#

    - by Josh
    I've been trying to automate a log in to a website I frequent, www.bungie.net. The site is associated with Microsoft and Xbox Live, and as such makes uses of the Windows Live ID API when people log in to their site. I am relatively new to creating web spiders/robots, and I worry that I'm misunderstanding some of the most basic concepts. I've simulated logins to other sites such as Facebook and Gmail, but live.com has given me nothing but trouble. Anyways, I've been using Wireshark and the Firefox addon Tamper Data to try and figure out what I need to post, and what cookies I need to include with my requests. As far as I know these are the steps one must follow to log in to this site. 1. Visit https: //login.live.com/login.srf?wa=wsignin1.0&rpsnv=11&ct=1268167141&rver=5.5.4177.0&wp=LBI&wreply=http:%2F%2Fwww.bungie.net%2FDefault.aspx&id=42917 2. Recieve the cookies MSPRequ and MSPOK. 3. Post the values from the form ID "PPSX", the values from the form ID "PPFT", your username, your password all to a changing URL similar to: https: //login.live.com/ppsecure/post.srf?wa=wsignin1.0&rpsnv=11&ct= (there are a few numbers that change at the end of that URL) 4. Live.com returns the user a page with more hidden forms to post. The client then posts the values from the form "ANON", the value from the form "ANONExp" and the values from the form "t" to the URL: http ://www.bung ie.net/Default.aspx?wa=wsignin1.0 5. After posting that data, the user is returned a variety of cookies the most important of which is "BNGAuth" which is the log in cookie for the site. Where I am having trouble is on fifth step, but that doesn't neccesarily mean I've done all the other steps correctly. I post the data from "ANON", "ANONExp" and "t" but instead of being returned a BNGAuth cookie, I'm returned a cookie named "RSPMaybe" and redirected to the home page. When I review the Wireshark log, I noticed something that instantly stood out to me as different between the log when I logged in with Firefox and when my program ran. It could be nothing but I'll include the picture here for you to review. I'm being returned an HTTP packet from the site before I post the data in the fourth step. I'm not sure how this is happening, but it must be a side effect from something I'm doing wrong in the HTTPS steps. ![alt text][1] http://img391.imageshack.us/img391/6049/31394881.gif using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Text; using System.Net; using System.IO; using System.IO.Compression; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Web; namespace SpiderFromScratch { class Program { static void Main(string[] args) { CookieContainer cookies = new CookieContainer(); Uri url = new Uri("https://login.live.com/login.srf?wa=wsignin1.0&rpsnv=11&ct=1268167141&rver=5.5.4177.0&wp=LBI&wreply=http:%2F%2Fwww.bungie.net%2FDefault.aspx&id=42917"); HttpWebRequest http = (HttpWebRequest)HttpWebRequest.Create(url); http.Timeout = 30000; http.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.8) Gecko/20100202 Firefox/3.5.8 (.NET CLR 3.5.30729)"; http.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; http.Headers.Add("Accept-Language", "en-us,en;q=0.5"); http.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); http.Headers.Add("Keep-Alive", "300"); http.Referer = "http://www.bungie.net/"; http.ContentType = "application/x-www-form-urlencoded"; http.CookieContainer = new CookieContainer(); http.Method = WebRequestMethods.Http.Get; HttpWebResponse response = (HttpWebResponse)http.GetResponse(); StreamReader readStream = new StreamReader(response.GetResponseStream()); string HTML = readStream.ReadToEnd(); readStream.Close(); //gets the cookies (they are set in the eighth header) string[] strCookies = response.Headers.GetValues(8); response.Close(); string name, value; Cookie manualCookie; for (int i = 0; i < strCookies.Length; i++) { name = strCookies[i].Substring(0, strCookies[i].IndexOf("=")); value = strCookies[i].Substring(strCookies[i].IndexOf("=") + 1, strCookies[i].IndexOf(";") - strCookies[i].IndexOf("=") - 1); manualCookie = new Cookie(name, "\"" + value + "\""); Uri manualURL = new Uri("http://login.live.com"); http.CookieContainer.Add(manualURL, manualCookie); } //stores the cookies to be used later cookies = http.CookieContainer; //Get the PPSX value string PPSX = HTML.Remove(0, HTML.IndexOf("PPSX")); PPSX = PPSX.Remove(0, PPSX.IndexOf("value") + 7); PPSX = PPSX.Substring(0, PPSX.IndexOf("\"")); //Get this random PPFT value string PPFT = HTML.Remove(0, HTML.IndexOf("PPFT")); PPFT = PPFT.Remove(0, PPFT.IndexOf("value") + 7); PPFT = PPFT.Substring(0, PPFT.IndexOf("\"")); //Get the random URL you POST to string POSTURL = HTML.Remove(0, HTML.IndexOf("https://login.live.com/ppsecure/post.srf?wa=wsignin1.0&rpsnv=11&ct=")); POSTURL = POSTURL.Substring(0, POSTURL.IndexOf("\"")); //POST with cookies http = (HttpWebRequest)HttpWebRequest.Create(POSTURL); http.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.8) Gecko/20100202 Firefox/3.5.8 (.NET CLR 3.5.30729)"; http.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; http.Headers.Add("Accept-Language", "en-us,en;q=0.5"); http.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); http.Headers.Add("Keep-Alive", "300"); http.CookieContainer = cookies; http.Referer = "https://login.live.com/login.srf?wa=wsignin1.0&rpsnv=11&ct=1268158321&rver=5.5.4177.0&wp=LBI&wreply=http:%2F%2Fwww.bungie.net%2FDefault.aspx&id=42917"; http.ContentType = "application/x-www-form-urlencoded"; http.Method = WebRequestMethods.Http.Post; Stream ostream = http.GetRequestStream(); //used to convert strings into bytes System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); //Post information byte[] buffer = encoding.GetBytes("PPSX=" + PPSX +"&PwdPad=IfYouAreReadingThisYouHaveTooMuc&login=YOUREMAILGOESHERE&passwd=YOURWORDGOESHERE" + "&LoginOptions=2&PPFT=" + PPFT); ostream.Write(buffer, 0, buffer.Length); ostream.Close(); HttpWebResponse response2 = (HttpWebResponse)http.GetResponse(); readStream = new StreamReader(response2.GetResponseStream()); HTML = readStream.ReadToEnd(); response2.Close(); ostream.Dispose(); foreach (Cookie cookie in response2.Cookies) { Console.WriteLine(cookie.Name + ": "); Console.WriteLine(cookie.Value); Console.WriteLine(cookie.Expires); Console.WriteLine(); } //SET POSTURL value string POSTANON = "http://www.bungie.net/Default.aspx?wa=wsignin1.0"; //Get the ANON value string ANON = HTML.Remove(0, HTML.IndexOf("ANON")); ANON = ANON.Remove(0, ANON.IndexOf("value") + 7); ANON = ANON.Substring(0, ANON.IndexOf("\"")); ANON = HttpUtility.UrlEncode(ANON); //Get the ANONExp value string ANONExp = HTML.Remove(0, HTML.IndexOf("ANONExp")); ANONExp = ANONExp.Remove(0, ANONExp.IndexOf("value") + 7); ANONExp = ANONExp.Substring(0, ANONExp.IndexOf("\"")); ANONExp = HttpUtility.UrlEncode(ANONExp); //Get the t value string t = HTML.Remove(0, HTML.IndexOf("id=\"t\"")); t = t.Remove(0, t.IndexOf("value") + 7); t = t.Substring(0, t.IndexOf("\"")); t = HttpUtility.UrlEncode(t); //POST the Info and Accept the Bungie Cookies http = (HttpWebRequest)HttpWebRequest.Create(POSTANON); http.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.8) Gecko/20100202 Firefox/3.5.8 (.NET CLR 3.5.30729)"; http.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; http.Headers.Add("Accept-Language", "en-us,en;q=0.5"); http.Headers.Add("Accept-Encoding", "gzip,deflate"); http.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); http.Headers.Add("Keep-Alive", "115"); http.CookieContainer = new CookieContainer(); http.ContentType = "application/x-www-form-urlencoded"; http.Method = WebRequestMethods.Http.Post; http.Expect = null; ostream = http.GetRequestStream(); int test = ANON.Length; int test1 = ANONExp.Length; int test2 = t.Length; buffer = encoding.GetBytes("ANON=" + ANON +"&ANONExp=" + ANONExp + "&t=" + t); ostream.Write(buffer, 0, buffer.Length); ostream.Close(); //Here lies the problem, I am not returned the correct cookies. HttpWebResponse response3 = (HttpWebResponse)http.GetResponse(); GZipStream gzip = new GZipStream(response3.GetResponseStream(), CompressionMode.Decompress); readStream = new StreamReader(gzip); HTML = readStream.ReadToEnd(); //gets both cookies string[] strCookies2 = response3.Headers.GetValues(11); response3.Close(); } } } This has given me problems and I've put many hours into learning about HTTP protocols so any help would be appreciated. If there is an article detailing a similar log in to live.com feel free to point the way. I've been looking far and wide for any articles with working solutions. If I could be clearer, feel free to ask as this is my first time using Stack Overflow. Cheers, --Josh

    Read the article

  • Logging Into a site that uses Live.com authentication

    - by Josh
    I've been trying to automate a log in to a website I frequent, www.bungie.net. The site is associated with Microsoft and Xbox Live, and as such makes uses of the Windows Live ID API when people log in to their site. I am relatively new to creating web spiders/robots, and I worry that I'm misunderstanding some of the most basic concepts. I've simulated logins to other sites such as Facebook and Gmail, but live.com has given me nothing but trouble. Anyways, I've been using Wireshark and the Firefox addon Tamper Data to try and figure out what I need to post, and what cookies I need to include with my requests. As far as I know these are the steps one must follow to log in to this site. 1. Visit https: //login.live.com/login.srf?wa=wsignin1.0&rpsnv=11&ct=1268167141&rver=5.5.4177.0&wp=LBI&wreply=http:%2F%2Fwww.bungie.net%2FDefault.aspx&id=42917 2. Recieve the cookies MSPRequ and MSPOK. 3. Post the values from the form ID "PPSX", the values from the form ID "PPFT", your username, your password all to a changing URL similar to: https: //login.live.com/ppsecure/post.srf?wa=wsignin1.0&rpsnv=11&ct= (there are a few numbers that change at the end of that URL) 4. Live.com returns the user a page with more hidden forms to post. The client then posts the values from the form "ANON", the value from the form "ANONExp" and the values from the form "t" to the URL: http ://www.bung ie.net/Default.aspx?wa=wsignin1.0 5. After posting that data, the user is returned a variety of cookies the most important of which is "BNGAuth" which is the log in cookie for the site. Where I am having trouble is on fifth step, but that doesn't neccesarily mean I've done all the other steps correctly. I post the data from "ANON", "ANONExp" and "t" but instead of being returned a BNGAuth cookie, I'm returned a cookie named "RSPMaybe" and redirected to the home page. When I review the Wireshark log, I noticed something that instantly stood out to me as different between the log when I logged in with Firefox and when my program ran. It could be nothing but I'll include the picture here for you to review. I'm being returned an HTTP packet from the site before I post the data in the fourth step. I'm not sure how this is happening, but it must be a side effect from something I'm doing wrong in the HTTPS steps. using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Text; using System.Net; using System.IO; using System.IO.Compression; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Web; namespace SpiderFromScratch { class Program { static void Main(string[] args) { CookieContainer cookies = new CookieContainer(); Uri url = new Uri("https://login.live.com/login.srf?wa=wsignin1.0&rpsnv=11&ct=1268167141&rver=5.5.4177.0&wp=LBI&wreply=http:%2F%2Fwww.bungie.net%2FDefault.aspx&id=42917"); HttpWebRequest http = (HttpWebRequest)HttpWebRequest.Create(url); http.Timeout = 30000; http.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.8) Gecko/20100202 Firefox/3.5.8 (.NET CLR 3.5.30729)"; http.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; http.Headers.Add("Accept-Language", "en-us,en;q=0.5"); http.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); http.Headers.Add("Keep-Alive", "300"); http.Referer = "http://www.bungie.net/"; http.ContentType = "application/x-www-form-urlencoded"; http.CookieContainer = new CookieContainer(); http.Method = WebRequestMethods.Http.Get; HttpWebResponse response = (HttpWebResponse)http.GetResponse(); StreamReader readStream = new StreamReader(response.GetResponseStream()); string HTML = readStream.ReadToEnd(); readStream.Close(); //gets the cookies (they are set in the eighth header) string[] strCookies = response.Headers.GetValues(8); response.Close(); string name, value; Cookie manualCookie; for (int i = 0; i < strCookies.Length; i++) { name = strCookies[i].Substring(0, strCookies[i].IndexOf("=")); value = strCookies[i].Substring(strCookies[i].IndexOf("=") + 1, strCookies[i].IndexOf(";") - strCookies[i].IndexOf("=") - 1); manualCookie = new Cookie(name, "\"" + value + "\""); Uri manualURL = new Uri("http://login.live.com"); http.CookieContainer.Add(manualURL, manualCookie); } //stores the cookies to be used later cookies = http.CookieContainer; //Get the PPSX value string PPSX = HTML.Remove(0, HTML.IndexOf("PPSX")); PPSX = PPSX.Remove(0, PPSX.IndexOf("value") + 7); PPSX = PPSX.Substring(0, PPSX.IndexOf("\"")); //Get this random PPFT value string PPFT = HTML.Remove(0, HTML.IndexOf("PPFT")); PPFT = PPFT.Remove(0, PPFT.IndexOf("value") + 7); PPFT = PPFT.Substring(0, PPFT.IndexOf("\"")); //Get the random URL you POST to string POSTURL = HTML.Remove(0, HTML.IndexOf("https://login.live.com/ppsecure/post.srf?wa=wsignin1.0&rpsnv=11&ct=")); POSTURL = POSTURL.Substring(0, POSTURL.IndexOf("\"")); //POST with cookies http = (HttpWebRequest)HttpWebRequest.Create(POSTURL); http.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.8) Gecko/20100202 Firefox/3.5.8 (.NET CLR 3.5.30729)"; http.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; http.Headers.Add("Accept-Language", "en-us,en;q=0.5"); http.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); http.Headers.Add("Keep-Alive", "300"); http.CookieContainer = cookies; http.Referer = "https://login.live.com/login.srf?wa=wsignin1.0&rpsnv=11&ct=1268158321&rver=5.5.4177.0&wp=LBI&wreply=http:%2F%2Fwww.bungie.net%2FDefault.aspx&id=42917"; http.ContentType = "application/x-www-form-urlencoded"; http.Method = WebRequestMethods.Http.Post; Stream ostream = http.GetRequestStream(); //used to convert strings into bytes System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); //Post information byte[] buffer = encoding.GetBytes("PPSX=" + PPSX +"&PwdPad=IfYouAreReadingThisYouHaveTooMuc&login=YOUREMAILGOESHERE&passwd=YOURWORDGOESHERE" + "&LoginOptions=2&PPFT=" + PPFT); ostream.Write(buffer, 0, buffer.Length); ostream.Close(); HttpWebResponse response2 = (HttpWebResponse)http.GetResponse(); readStream = new StreamReader(response2.GetResponseStream()); HTML = readStream.ReadToEnd(); response2.Close(); ostream.Dispose(); foreach (Cookie cookie in response2.Cookies) { Console.WriteLine(cookie.Name + ": "); Console.WriteLine(cookie.Value); Console.WriteLine(cookie.Expires); Console.WriteLine(); } //SET POSTURL value string POSTANON = "http://www.bungie.net/Default.aspx?wa=wsignin1.0"; //Get the ANON value string ANON = HTML.Remove(0, HTML.IndexOf("ANON")); ANON = ANON.Remove(0, ANON.IndexOf("value") + 7); ANON = ANON.Substring(0, ANON.IndexOf("\"")); ANON = HttpUtility.UrlEncode(ANON); //Get the ANONExp value string ANONExp = HTML.Remove(0, HTML.IndexOf("ANONExp")); ANONExp = ANONExp.Remove(0, ANONExp.IndexOf("value") + 7); ANONExp = ANONExp.Substring(0, ANONExp.IndexOf("\"")); ANONExp = HttpUtility.UrlEncode(ANONExp); //Get the t value string t = HTML.Remove(0, HTML.IndexOf("id=\"t\"")); t = t.Remove(0, t.IndexOf("value") + 7); t = t.Substring(0, t.IndexOf("\"")); t = HttpUtility.UrlEncode(t); //POST the Info and Accept the Bungie Cookies http = (HttpWebRequest)HttpWebRequest.Create(POSTANON); http.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.8) Gecko/20100202 Firefox/3.5.8 (.NET CLR 3.5.30729)"; http.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; http.Headers.Add("Accept-Language", "en-us,en;q=0.5"); http.Headers.Add("Accept-Encoding", "gzip,deflate"); http.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); http.Headers.Add("Keep-Alive", "115"); http.CookieContainer = new CookieContainer(); http.ContentType = "application/x-www-form-urlencoded"; http.Method = WebRequestMethods.Http.Post; http.Expect = null; ostream = http.GetRequestStream(); int test = ANON.Length; int test1 = ANONExp.Length; int test2 = t.Length; buffer = encoding.GetBytes("ANON=" + ANON +"&ANONExp=" + ANONExp + "&t=" + t); ostream.Write(buffer, 0, buffer.Length); ostream.Close(); //Here lies the problem, I am not returned the correct cookies. HttpWebResponse response3 = (HttpWebResponse)http.GetResponse(); GZipStream gzip = new GZipStream(response3.GetResponseStream(), CompressionMode.Decompress); readStream = new StreamReader(gzip); HTML = readStream.ReadToEnd(); //gets both cookies string[] strCookies2 = response3.Headers.GetValues(11); response3.Close(); } } } This has given me problems and I've put many hours into learning about HTTP protocols so any help would be appreciated. If there is an article detailing a similar log in to live.com feel free to point the way. I've been looking far and wide for any articles with working solutions. If I could be clearer, feel free to ask as this is my first time using Stack Overflow.

    Read the article

  • Link checker ; how to avoid false positives

    - by Burnzy
    I'm working a on a link checker/broken link finder and I am getting many false positives, after double checking I noticed that many error codes were returning webexceptions but they were actually downloadable, but in some other cases the statuscode is 404 and i can access the page from the browse. So here is the code, its pretty ugly, and id like to have something more, id say practical. All the status codes are in that big if are used to filter the ones i dont want to add to brokenlink because they are valid links ( i tested them all ). What i need to fix is the structure (if possible) and how to not get false 404. Thank you! try { HttpWebRequest request = ( HttpWebRequest ) WebRequest.Create ( uri ); request.Method = "Head"; request.MaximumResponseHeadersLength = 32; // FOR IE SLOW SPEED request.AllowAutoRedirect = true; using ( HttpWebResponse response = ( HttpWebResponse ) request.GetResponse() ) { request.Abort(); } /* WebClient wc = new WebClient(); wc.DownloadString( uri ); */ _validlinks.Add ( strUri ); } catch ( WebException wex ) { if ( !wex.Message.Contains ( "The remote name could not be resolved:" ) && wex.Status != WebExceptionStatus.ServerProtocolViolation ) { if ( wex.Status != WebExceptionStatus.Timeout ) { HttpStatusCode code = ( ( HttpWebResponse ) wex.Response ).StatusCode; if ( code != HttpStatusCode.OK && code != HttpStatusCode.BadRequest && code != HttpStatusCode.Accepted && code != HttpStatusCode.InternalServerError && code != HttpStatusCode.Forbidden && code != HttpStatusCode.Redirect && code != HttpStatusCode.Found ) { _brokenlinks.Add ( new Href ( new Uri ( strUri , UriKind.RelativeOrAbsolute ) , UrlType.External ) ); } else _validlinks.Add ( strUri ); } else _brokenlinks.Add ( new Href ( new Uri ( strUri , UriKind.RelativeOrAbsolute ) , UrlType.External ) ); } else _validlinks.Add ( strUri ); }

    Read the article

  • .NET: Is it possible to get HttpWebRequest to automatically decompress gzip'd responses?

    - by Cheeso
    In this answer, I described how I resorted to wrappnig a GZipStream around the response stream in a HttpWebResponse, in order to decompress it. The relevant code looks like this: HttpWebRequest hwr = (HttpWebRequest) WebRequest.Create(url); hwr.CookieContainer = PersistentCookies.GetCookieContainerForUrl(url); hwr.Accept = "text/xml, */*"; hwr.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate"); hwr.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-us"); hwr.UserAgent = "My special app"; hwr.KeepAlive = true; var resp = (HttpWebResponse) hwr.GetResponse(); using(Stream s = resp.GetResponseStream()) { Stream s2 = s; if (resp.ContentEncoding.ToLower().Contains("gzip")) s2 = new GZipStream(s2, CompressionMode.Decompress); else if (resp.ContentEncoding.ToLower().Contains("deflate")) s2 = new DeflateStream(s2, CompressionMode.Decompress); ... use s2 ... } Is there a way to get HttpWebResponse to provide a de-compressing stream, automatically? In other words, a way for me to eliminate the following from the above code: Stream s2 = s; if (resp.ContentEncoding.ToLower().Contains("gzip")) s2 = new GZipStream(s2, CompressionMode.Decompress); else if (resp.ContentEncoding.ToLower().Contains("deflate")) s2 = new DeflateStream(s2, CompressionMode.Decompress); Thanks.

    Read the article

  • C# Simple Twitter Update

    - by mroberts
    For what it's worth a simple twitter update. 1: using System; 2: using System.IO; 3: using System.Net; 4: using System.Text; 5:   6: namespace Server.Actions 7: { 8: public class TwitterUpdate 9: { 10: public string Body { get; set; } 11: public string Login { get; set; } 12: public string Password { get; set; } 13:   14: public override void Execute() 15: { 16: try 17: { 18: //encode user name and password 19: string creds = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", this.Login, this.Password))); 20:   21: //encode tweet 22: byte[] tweet = Encoding.ASCII.GetBytes("status=" + this.Body); 23:   24: //setup request 25: HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://twitter.com/statuses/update.xml"); 26: request.Method = "POST"; 27: request.ServicePoint.Expect100Continue = false; 28: request.Headers.Add("Authorization", string.Format("Basic {0}", creds)); 29: request.ContentType = "application/x-www-form-urlencoded"; 30: request.ContentLength = tweet.Length; 31:   32: //write to stream 33: Stream reqStream = request.GetRequestStream(); 34: reqStream.Write(tweet, 0, tweet.Length); 35: reqStream.Close(); 36:   37: //check response 38: HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 39:   40: //... 41: } 42: catch (Exception e) 43: { 44: //... 45: } 46: } 47: } 48: }   BTW, this is my first blog post.  Nothing earth shattering, I admit, but I needed to figure out how to post formatted code.  In the past I’ve used Alex Gorbatchev’s Syntax Highlighter with great success, but here at GWB I couldn’t get it to work. Windows Live Writer though, being a stand alone writer, worked with no problems.  For now, that’s what I’ll use.

    Read the article

  • C# Simple Twitter Update

    - by mroberts
    For what it's worth a simple twitter update. using System; using System.IO; using System.Net; using System.Text; namespace Server.Actions { public class TwitterUpdate { public string Body { get; set; } public string Login { get; set; } public string Password { get; set; } public override void Execute() { try { //encode user name and password string creds = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", this.Login, this.Password))); //encode tweet byte[] tweet = Encoding.ASCII.GetBytes("status=" + this.Body); //setup request HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://twitter.com/statuses/update.xml"); request.Method = "POST"; request.ServicePoint.Expect100Continue = false; request.Headers.Add("Authorization", string.Format("Basic {0}", creds)); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = tweet.Length; //write to stream Stream reqStream = request.GetRequestStream(); reqStream.Write(tweet, 0, tweet.Length); reqStream.Close(); //check response HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //... } catch (Exception e) { //... } } } }

    Read the article

  • Dispatcher.BeginInvoke problems

    - by cmaduro
    I'm getting "An object reference is required for the non-static field, method, or property 'System.Windows.Threading.Dispatcher.BeginInvoke(System.Action)'" for this code. private void ResponseCompleted(IAsyncResult result) { HttpWebRequest request = result.AsyncState as HttpWebRequest; HttpWebResponse response = request.EndGetResponse(result) as HttpWebResponse; using (StreamReader sr = new StreamReader(response.GetResponseStream())) { Dispatcher.BeginInvoke( () => { try { XDocument resultsXml = XDocument.Load(sr); QueryCompleted(new QueryCompletedEventArgs(resultsXml)); } catch (XmlException e) { XDocument errorXml = new XDocument(new XElement("error", e.Message)); QueryCompleted(new QueryCompletedEventArgs(errorXml)); } }); } } }

    Read the article

  • ASP.net WebRequest Exception "System.Net.WebException: The server committed a protocol violation"

    - by Billy
    I call WebRequest.GetResponse() and encounter the error: The server committed a protocol violation. Section=ResponseStatusLine I google this error and add the following lines in web.config: <configuration> <system.net> <settings> <httpWebRequest useUnsafeHeaderParsing="true" /> </settings> </system.net> </configuration> However, it doesn't work. Here is my ASP.net code: HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.Method = "HEAD"; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { ...... }

    Read the article

  • get site source code as register user(c#)

    - by nir143
    hi. i downloaded a sourcecode of a site,but i downloaded it i saw it identify my program as a guest,i search at google and figure out that i can send a cookie when i "ask" the source code. that what i have managed to do and it still dont identify me as register user: CookieContainer cj = new; CookieContainer(); string all = ""; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Url); req.CookieContainer = cj; HttpWebResponse res = (HttpWebResponse)req.GetResponse(); CookieCollection cs=cj.GetCookies(req.RequestUri); CookieContainer cc = new CookieContainer(); cc.Add(cs); req.CookieContainer = cc; StreamReader read = new StreamReader(res.GetResponseStream()); all = read.ReadToEnd(); read.Close(); return all; what is wrong here? tyvm for help:)

    Read the article

  • How to extract digg data by digg api

    - by vamsivanka
    I am trying to extract digg data for a user using this url "http://services.digg.com/user/vamsivanka/diggs?count=25&appkey=34asd56asdf789as87df65s4fas6" and the web response is throwing an error "The remote server returned an error: (403) Forbidden." Please let me know. public static XmlTextReader CreateWebRequest(string url) { HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url); webRequest.UserAgent = ".NET Framework digg Test Client"; webRequest.Credentials = System.Net.CredentialCache.DefaultCredentials; webRequest.Accept = "text/xml"; HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse(); System.IO.Stream responseStream = webResponse.GetResponseStream(); XmlTextReader reader = new XmlTextReader(responseStream); return reader; }

    Read the article

  • WCF web service Data Members defaulting to null

    - by James
    I am new to WCF and created a simple REST service to accept an order object (series of strings from XML file), insert that data into a database, and then return an order object that contains the results. To test the service I created a small web project and send over a stream created from an xml doc. The problem is that even though all of the items in the xml doc get placed into the stream, the service is nullifying some of them when it receives the data. For example lineItemId will have a value but shipment status will show null. I step through the xml creation and verify that all the values are being sent. However, if I clear the datamembers and change the names around, it can work. Any help would be appreciated. This is the interface code [ServiceContract] public interface IShipping { [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/Orders/UpdateOrderStatus/", BodyStyle=WebMessageBodyStyle.Bare)] ReturnOrder UpdateOrderStatus(Order order); } [DataContract] public class Order { [DataMember] public string lineItemId { get; set; } [DataMember] public string shipmentStatus { get; set; } [DataMember] public string trackingNumber { get; set; } [DataMember] public string shipmentDate { get; set; } [DataMember] public string delvryMethod { get; set; } [DataMember] public string shipmentCarrier { get; set; } } [DataContract] public class ReturnOrder { [DataMember(Name = "Result")] public string Result { get; set; } } This is what I'm using to send over an Order object: string lineId = txtLineItem.Text.Trim(); string status = txtDeliveryStatus.Text.Trim(); string TrackingNumber = "1x22-z4r32"; string theMethod = "Ground"; string carrier = "UPS"; string ShipmentDate = "04/27/2010"; XNamespace nsOrders = "http://tempuri.org/order"; XElement myDoc = new XElement(nsOrders + "Order", new XElement(nsOrders + "lineItemId", lineId), new XElement(nsOrders + "shipmentStatus", status), new XElement(nsOrders + "trackingNumber", TrackingNumber), new XElement(nsOrders + "delvryMethod", theMethod), new XElement(nsOrders + "shipmentCarrier", carrier), new XElement(nsOrders + "shipmentDate", ShipmentDate) ); HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:3587/Deposco.svc/wms/Orders/UpdateOrderStatus/"); request.Method = "POST"; request.ContentType = "application/xml"; try { request.ContentLength = myDoc.ToString().Length; StreamWriter sw = new StreamWriter(request.GetRequestStream()); sw.Write(myDoc); sw.Close(); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { StreamReader reader = new StreamReader(response.GetResponseStream()); string responseString = reader.ReadToEnd(); XDocument.Parse(responseString).Save(@"c:\DeposcoSvcWCF.xml"); } } catch (WebException wEx) { Stream errorStream = ((HttpWebResponse)wEx.Response).GetResponseStream(); string errorMsg = new StreamReader(errorStream).ReadToEnd(); }

    Read the article

  • extract digg data by digg api

    - by vamsivanka
    I am trying to extract digg data for a user using this url "http://services.digg.com/user/vamsivanka/diggs?count=25&appkey=34asd56asdf789as87df65s4fas6" and the web response is throwing an error "The remote server returned an error: (403) Forbidden." Please let me know. public static XmlTextReader CreateWebRequest(string url) { HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url); webRequest.UserAgent = ".NET Framework digg Test Client"; webRequest.Credentials = System.Net.CredentialCache.DefaultCredentials; webRequest.Accept = "text/xml"; HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse(); System.IO.Stream responseStream = webResponse.GetResponseStream(); XmlTextReader reader = new XmlTextReader(responseStream); return reader; }

    Read the article

  • How to simulate browser file upload with HttpWebRequest

    - by cucicov
    Hi, guys, first of all thanks for your contributions, I've found great responses here. Yet I've ran into a problem I can't figure out and if someone could provide any help, it would be greatly appreciated. I'm developing this application in C# that could upload an image from computer to user photoblog. For this I'm usig pixelpost platform for photoblogs that is written mainly in PHP. I've searched here and on other web pages, but the exmples provided there didn't work for me. Here is what I used in my example: (http://stackoverflow.com/questions/566462/upload-files-with-httpwebrequest-multipart-form-data) and (http://bytes.com/topic/c-sharp/answers/268661-how-upload-file-via-c-code) Once it is ready I will make it available for free on the internet and maybe also create a windows mobile version of it, since I'm a fan of pixelpost. here is the code I've used: string formUrl = "http://localhost/pixelpost/admin/index.php?x=login"; string formParams = string.Format("user={0}&password={1}", "user-String", "password-String"); string cookieHeader; HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(formUrl); req.ContentType = "application/x-www-form-urlencoded"; req.Method = "POST"; req.AllowAutoRedirect = false; byte[] bytes = Encoding.ASCII.GetBytes(formParams); req.ContentLength = bytes.Length; using (Stream os = req.GetRequestStream()) { os.Write(bytes, 0, bytes.Length); } HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); cookieHeader = resp.Headers["Set-Cookie"]; string pageSource; using (StreamReader sr = new StreamReader(resp.GetResponseStream())) { pageSource = sr.ReadToEnd(); Console.WriteLine(); } string getUrl = "http://localhost/pixelpost/admin/index.php"; HttpWebRequest getRequest = (HttpWebRequest)HttpWebRequest.Create(getUrl); getRequest.Headers.Add("Cookie", cookieHeader); HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse(); using (StreamReader sr = new StreamReader(getResponse.GetResponseStream())) { pageSource = sr.ReadToEnd(); } // end first part: login to admin panel long length = 0; string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x"); HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create("http://localhost/pixelpost/admin/index.php?x=save"); httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary; httpWebRequest2.Method = "POST"; httpWebRequest2.AllowAutoRedirect = false; httpWebRequest2.KeepAlive = false; httpWebRequest2.Credentials = System.Net.CredentialCache.DefaultCredentials; httpWebRequest2.Headers.Add("Cookie", cookieHeader); Stream memStream = new System.IO.MemoryStream(); byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}"; string formitem = string.Format(formdataTemplate, "headline", "image-name"); byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem); memStream.Write(formitembytes, 0, formitembytes.Length); memStream.Write(boundarybytes, 0, boundarybytes.Length); string headerTemplate = "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n"; string header = string.Format(headerTemplate, "userfile", "path-to-the-local-file"); byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header); memStream.Write(headerbytes, 0, headerbytes.Length); FileStream fileStream = new FileStream("path-to-the-local-file", FileMode.Open, FileAccess.Read); byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { memStream.Write(buffer, 0, bytesRead); } memStream.Write(boundarybytes, 0, boundarybytes.Length); fileStream.Close(); httpWebRequest2.ContentLength = memStream.Length; Stream requestStream = httpWebRequest2.GetRequestStream(); memStream.Position = 0; byte[] tempBuffer = new byte[memStream.Length]; memStream.Read(tempBuffer, 0, tempBuffer.Length); memStream.Close(); requestStream.Write(tempBuffer, 0, tempBuffer.Length); requestStream.Close(); WebResponse webResponse2 = httpWebRequest2.GetResponse(); Stream stream2 = webResponse2.GetResponseStream(); StreamReader reader2 = new StreamReader(stream2); Console.WriteLine(reader2.ReadToEnd()); webResponse2.Close(); httpWebRequest2 = null; webResponse2 = null; and also here is the PHP: (http://dl.dropbox.com/u/3149888/index.php) and (http://dl.dropbox.com/u/3149888/new_image.php) the mandatory fields are headline and userfile so I can't figure out where the mistake is, as the format sent in right. I'm guessing there is something wrong with the octet-stream sent to the form. Maybe it's a stupid mistake I wasn't able to trace, in any case, if you could help me that would mean a lot. thanks,

    Read the article

  • How to receive userinfo with google adwords api libraries

    - by PatrickvKleef
    I'm using the Google Adwords API libraries and I would like to receive the userinfo of the logged in user. I added the userinfo scope as followed: googleAdwordsUser = new AdWordsUser(); string oauth_callback_url = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path); googleAdwordsUser.OAuthProvider = new AdsOAuthNetProvider("https://adwords-sandbox.google.com/api/adwords/ https://www.googleapis.com/auth/userinfo.email", oauth_callback_url, Session.SessionID); When the callback url is called, I'm trying to get the users emailaddress, but it isn't working, the error 'The remote server returned an error: (401) Unauthorized.' is thrown. string url = @"https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + token; HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url); objRequest.Method = "GET"; HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse(); string result = string.Empty; using (StreamReader sr = new StreamReader(objResponse.GetResponseStream())) { result = sr.ReadToEnd(); } Does somebody knows how to fix this? Thanks.

    Read the article

  • How to stream video content in asp.net?

    - by Kon
    Hi, I have the following code which downloads video content: WebRequest wreq = (HttpWebRequest)WebRequest.Create(url); using (HttpWebResponse wresp = (HttpWebResponse)wreq.GetResponse()) using (Stream mystream = wresp.GetResponseStream()) { using (BinaryReader reader = new BinaryReader(mystream)) { int length = Convert.ToInt32(wresp.ContentLength); byte[] buffer = new byte[length]; buffer = reader.ReadBytes(length); Response.Clear(); Response.Buffer = false; Response.ContentType = "video/mp4"; //Response.BinaryWrite(buffer); Response.OutputStream.Write(buffer, 0, buffer.Length); Response.End(); } } But the problem is that the whole file downloads before being played. How can I make it stream and play as it's still downloading? Or is this up to the client/receiver application to manage?

    Read the article

  • .NET - downloading multiple pages from a website with a single DNS query

    - by lampak
    I'm using HttpRequest to download several pages from a website (in a loop). Simplifying it looks like this: HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create( "http://sub.domain.com/something/" + someString ); HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); //do something I'm not quite sure actually but every request seems to resolve the address again (I don't know how to test if I'm right). I would like to boost it a little and resolve the address once and then reuse it for all requests. I can't work out how to force HttpRequest into using it, though. I have tried using Dns.GetHostAddresses, converting the result to a string and passing it as the address to HttpWebRequest.Create. Unfortunately, server returns error 404 then. I managed to google that's probably because the "Host" header of the http query doesn't match what the server expects. Is there a simple way to solve this?

    Read the article

  • Bypass Forbidden and Server Internal Error with httpwebrequest

    - by Burnzy
    i'm a getting forbidden (403) and Server Internal Error(500) when doing a request to a site even if when trying it with the browser, everything is fine. Here's my code and my appdata tag concerning httpwebrequest HttpWebRequest request = (HttpWebRequest)WebRequest.Create( uri ); request.Method = "HEAD"; request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.2; Trident/4.0)"; request.AllowAutoRedirect = true; request.SendChunked = true; request.UnsafeAuthenticatedConnectionSharing = true; request.KeepAlive = false; request.Timeout = 7500; using( HttpWebResponse response = (HttpWebResponse)request.GetResponse() ) { request.Abort(); } app settings: Thank you!

    Read the article

  • Using Api to submit userdata to external party

    - by Younes
    I have to submit subscription data to another website. I have got documentation on how to use this API however i'm not 100% sure of how to set this up. I do have all the information needed, like username / passwords etc. This is the API documentation: https://www.apiemail.net/api/documentation/?SID=4 How would my request / post / whatever look like in C# .net (vs 2008) when i'm trying to acces this API? This is what i have now, I think i'm not on the right track: public static string GArequestResponseHelper(string url, string token, string username, string password) { HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url); myRequest.Headers.Add("Username: " + username); myRequest.Headers.Add("Password: " + password); HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse(); Stream responseBody = myResponse.GetResponseStream(); Encoding encode = System.Text.Encoding.GetEncoding("utf-8"); StreamReader readStream = new StreamReader(responseBody, encode); //return string itself (easier to work with) return readStream.ReadToEnd();

    Read the article

  • Get HttpResponse from a page in the same web application

    - by tivo
    I have the following code: HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://mycomputer/myWebApp/WebPage2.aspx"); myHttpWebRequest.Credentials = CredentialCache.DefaultNetworkCredentials; HttpWebResponse myHttpWebResponse = HttpWebResponse)myHttpWebRequest.GetResponse(); The last line of code throws a (500) Internal Server Error... This code is part of myWebApp/WepPage1.aspx, yes both aspx pages are on the same webapp. What I want to accomplish is to get WebPage2.aspx html response, put it on an email and send it from WebPage1.aspx. I would really appreciate any tips.. Thanks!!!

    Read the article

  • Monotouch/C# version of "stringWithContentsOfUrl"

    - by Pselus
    I'm trying to convert a piece of Objective-C code into C# for use with Monotouch and I have no idea what to use to replace stringWithContentsOfUrl Should I use something like: HttpWebRequest request = (HttpWebRequest) WebRequest.Create("http://www.helephant.com"); HttpWebResponse response = (HttpWebResponse) request.GetResponse(); if (response.StatusCode == HttpStatusCode.OK && response.ContentLength > 0){ TextReader reader = new StreamReader(response.GetResponseStream()); string text = reader.ReadToEnd(); Console.Write(text); } Is that even safe to use in MonoTouch? Will it work for the iPhone?

    Read the article

  • Getting error when compiled Http webrequest

    - by Afnan
    i have written a program to search value from google every thing works fine but first time when page is loaded then i encounter error.after words if i click any link it is working fine no errors further. Code is as follow private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { string raw = "http://www.google.com/search?hl=en&q={0}&aq=f&oq=&aqi=n1g10"; string search = string.Format(raw, HttpUtility.UrlEncode(searchTerm)); //string search = "http://www.whatismyip.com/"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(search); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII)) { browserA = reader.ReadToEnd(); this.Invoke(new EventHandler(IE1)); } } }

    Read the article

  • HttpwebRequest Simulate Click

    - by Afnan
    I was working on httpwebrequest and was trying to search google get result and simulate click to desired link. Is that possible? string raw ="http://www.google.com/search?hl=en&q={0}&aq=f&oq=&aqi=n1g10"; string search = string.Format(raw, HttpUtility.UrlEncode(searchTerm)); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(search); request.Proxy = prox; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII)) { HtmlElementCollection html = reader.ReadToEnd(); browserA=reader.ReadToEnd(); this.Invoke(new EventHandler(IE1)); } }

    Read the article

  • How to properly catch a 404 error in .NET

    - by Luke101
    I would like to know the proper way to catch a 404 error with c# asp.net here is the code I'm using HttpWebRequest request = (HttpWebRequest) WebRequest.Create(String.Format("http://www.gravatar.com/avatar/{0}?d=404", hashe)); // execute the request try { //TODO: test for good connectivity first //So it will not update the whole database with bad avatars HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Response.Write("has avatar"); } catch (Exception ex) { if (ex.ToString().Contains("404")) { Response.Write("No avatar"); } } This code works but I just would like to know if this is the most efficient.

    Read the article

  • Using thread in aspx-page making a webrequest

    - by Mike Ribeiro
    Hi, I kind of new to the hole threading stuff so bare with me here.. I have a aspx-page that takes some input and makes a reqest: HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format("{0}?{1}", strPostPath, strPostData)); request.Method = "GET"; request.Timeout = 5000; // set 5 sec. timeout request.ProtocolVersion = HttpVersion.Version11; try { HttpWebResponse response = (HttpWebResponse)request.GetResponse(); /do some with response } catch (WebException exce) { //Log some stuff } The thing is that this function is used ALOT. Is there any advantage to make every request in a separate thread and exactly how would that look like? Thx!

    Read the article

  • Phase REST XML into variable

    - by 001
    I want to get a response from the REST XML web service, and phase it into variables so I can use them in my program. 1) How come this code does not work? I get an empty string... // Get response string ws_response=""; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { // Get the response stream StreamReader reader = new StreamReader(response.GetResponseStream()); // web service response string ws_response = reader.ReadToEnd; // <---???? I get an empty string // do phasing here (ie XML element into variable) etc.. // }

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8  | Next Page >