Search Results

Search found 455 results on 19 pages for 'httpwebrequest'.

Page 10/19 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • Calling https process from ASP Net

    - by David M
    I have an ASP NET web server application that calls another process running on the same box that creates a pdf file and returns it. The second process requires a secure connection via SSL. The second process has issued my ASP NET application with a digital certificate but I still cannot authenticate, getting a 403 error. The code is a little hard to show but here's a simplified method ... X509Certificate cert = X509Certificate.CreateFromCertFile("path\to\cert.cer"); string URL = "https://urltoservice?params=value"; HttpWebRequest req = HttpWebRequest.Create(URL) as HttpWebRequest; req.ClientCertificates.Add(cert); req.Credentials = CredentialCache.DefaultCredentials; req.PreAuthenticate = true; /// error happens here WebResponse resp = req.GetResponse(); Stream input = resp.GetResponseStream(); The error text is "The remote server returned an error: (403) Forbidden." Any pointers are welcome.

    Read the article

  • Why wouldn't I be able to establish a trust relationship for a SSL/TLS channel?

    - by Abe Miessler
    I have a piece of .NET code that is erroring out when it makes a call to HTTPWebRequest.GetRequestStream. Here is the error message: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. I've read a few things that suggest that I might need a certificate on the machine running the code, but i'm not sure if that's true or how to do it. If I need to get a certificate, how do I do it? Code: var request = (HttpWebRequest)HttpWebRequest.Create(requestUrl); //my url request.Method = StringUtilities.ConvertToString(httpMethod); // Set the http method GET, POST, etc. if (postData != null) { request.ContentLength = postData.Length; request.ContentType = contentType; using (var dataStream = request.GetRequestStream()) { dataStream.Write(postData, 0, postData.Length); } }

    Read the article

  • How to Identify the website's content language

    - by Ajay
    I am developing a website to crawl the other website content in ASP.NET . I am able to get the content correctly but how can I identify which language is used based on that content. I used following code. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(TextBox1.Text ); request.UserAgent = "A .NET Web Crawler"; WebResponse response = request.GetResponse(); Stream stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string htmlText = reader.ReadToEnd();

    Read the article

  • SOAP Service Request C#

    - by user3728352
    I have this code that tries to send a request to a soap server, I'm new to soap so i am not sure if the terms i am using are correct or not please correct me I am wrong. Basically i am accessing a web service method named getUserDomain via soap request Here is the code: public void CallWebService() { var _url = "https://....com/QcXmlWebService/QcXmlWebService.asmx?wsdl"; var _action = "https://....com/QcXmlWebService/QcXmlWebService.asmx?op=GetUserDomains"; XmlDocument soapEnvelopeXml = CreateSoapEnvelope(); HttpWebRequest webRequest = CreateWebRequest(_url, _action); InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest); webRequest.BeginGetResponse(null, null); // begin async call to web request. IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null); // suspend this thread until call is complete. You might want to // do something usefull here like update your UI. asyncResult.AsyncWaitHandle.WaitOne(); // get the response from the completed web request. string soapResult; using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult)) { using (StreamReader rd = new StreamReader(webResponse.GetResponseStream())) { soapResult = rd.ReadToEnd(); } Console.Write(soapResult); } } private HttpWebRequest CreateWebRequest(string url, string action) { HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url); webRequest.Headers.Add("SOAPAction", action); webRequest.ContentType = "text/xml;charset=\"utf-8\""; webRequest.Accept = "text/xml"; webRequest.Method = "POST"; return webRequest; } private XmlDocument CreateSoapEnvelope() { XmlDocument soapEnvelop = new XmlDocument(); string oRequest = ""; oRequest = @"<soap:Envelope xmlns:soap=""http://www.w3.org/2003/05/soap-envelope"" xmlns:qcx=""http://smething.com/QCXML"">"; oRequest = oRequest + "<soap:Header/>"; oRequest = oRequest + "<soap:Body>"; oRequest = oRequest + "<qcx:GetUserDomains>"; oRequest = oRequest + "<qcx:inputXml><![CDATA["; oRequest = oRequest + "<GetUserDomains>"; oRequest = oRequest + "<login>"; oRequest = oRequest + "<domain_name>MBB_BTS</domain_name>"; oRequest = oRequest + "<project_name>WCDMA_BTS_IV</project_name>"; oRequest = oRequest + "<user_name>user</user_name>"; oRequest = oRequest + "<password>pass</password>"; oRequest = oRequest + "</login>"; oRequest = oRequest + "</GetUserDomains>"; oRequest = oRequest + " ]]>"; oRequest = oRequest + "</qcx:inputXml>"; oRequest = oRequest + "</qcx:GetUserDomains>"; oRequest = oRequest + "</soap:Body>"; oRequest = oRequest + "</soap:Envelope>"; soapEnvelop.LoadXml(oRequest); return soapEnvelop; } private void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest) { using (Stream stream = webRequest.GetRequestStream()) { soapEnvelopeXml.Save(stream); } } This code i have seen somewhere in stack overflow before as an answer but i couldn't get it to work... The error im getting is threw exception System.net.webexception. the remote server returned an error :(500) internal server Thanks

    Read the article

  • 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

  • FileUpload to FileStream

    - by Sri Kumar
    Hello, I am in process of sending the file along with HttpWebRequest. My file will be from FileUpload UI. Here i need to convert the File Upload to filestream to send the stream along with HttpWebRequest. How do i convert the FileUpload to a filestream?

    Read the article

  • How to get Alfresco login ticket without user password, but with impersonating user with user principal name (UPN)

    - by dok
    I'm writing a DLL that has function for getting Alfresco login ticket without using user password, using only a user principal name (UPN). I’m calling alfresco REST API service /wcservice. I use NTLM in Alfresco. I’m impersonating users using WindowsIdentity constructor as explained here http://msdn.microsoft.com/en-us/library/ms998351.aspx#paght000023_impersonatingbyusingwindowsidentity. I checked and user is properly impersonated (I checked WindowsIdentity.GetCurrent().Name property). After impersonating a user, I try to make HttpWebRequest and set its credentials with CredentialsCache.DefaultNetworkCredentials. I get the error: The remote server returned an error: (401) Unauthorized. at System.Net.HttpWebRequest.GetResponse() When I use new NetworkCredential("username", "P@ssw0rd") to set request credentials, I get Alfresco login ticket (HttpStatusCode.OK, 200). Is there any way that I can get Alfresco login ticket without user password? Here is the code that I'm using: private string GetTicket(string UPN) { WindowsIdentity identity = new WindowsIdentity(UPN); WindowsImpersonationContext context = null; try { context = identity.Impersonate(); MakeWebRequest(); } catch (Exception e) { return e.Message + Environment.NewLine + e.StackTrace; } finally { if (context != null) { context.Undo(); } } } private string MakeWebRequest() { string URI = "http://alfrescoserver/alfresco/wcservice/mg/util/login"; HttpWebRequest request = WebRequest.Create(URI) as HttpWebRequest; request.CookieContainer = new CookieContainer(1); //request.Credentials = new NetworkCredential("username", "p@ssw0rd"); // It works with this request.Credentials = CredentialCache.DefaultNetworkCredentials; // It doesn’t work with this //request.Credentials = CredentialCache.DefaultCredentials; // It doesn’t work with this either try { using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { StreamReader sr = new StreamReader(response.GetResponseStream()); return sr.ReadToEnd(); } } catch (Exception e) { return (e.Message + Environment.NewLine + e.StackTrace); } } Here are records from Alfresco stdout.log (if it helps in any way): 17:18:04,550 DEBUG [app.servlet.NTLMAuthenticationFilter] Processing request: /alfresco/wcservice/mg/util/login SID:7453F7BD4FD2E6A61AD40A31A37733A5 17:18:04,550 DEBUG [web.scripts.DeclarativeRegistry] Web Script index lookup for uri /mg/util/login took 0.526239ms 17:18:04,550 DEBUG [app.servlet.NTLMAuthenticationFilter] New NTLM auth request from 10.**.**.** (10.**.**.**:1229) 17:18:04,566 DEBUG [app.servlet.NTLMAuthenticationFilter] Processing request: /alfresco/wcservice/mg/util/login SID:7453F7BD4FD2E6A61AD40A31A37733A5 17:18:04,566 DEBUG [web.scripts.DeclarativeRegistry] Web Script index lookup for uri /mg/util/login took 0.400909ms 17:18:04,566 DEBUG [app.servlet.NTLMAuthenticationFilter] Received type1 [Type1:0xe20882b7,Domain:<NotSet>,Wks:<NotSet>] 17:18:04,566 DEBUG [app.servlet.NTLMAuthenticationFilter] Client domain null 17:18:04,675 DEBUG [app.servlet.NTLMAuthenticationFilter] Sending NTLM type2 to client - [Type2:0x80000283,Target:AlfrescoServerA,Ch:197e2631cc3f9e0a]

    Read the article

  • Accessing a web service and a HTTP interface using certificate authentication

    - by ADC
    It is the first time I have to use certificate authentication. A commercial partner expose two services, a XML Web Service and a HTTP service. I have to access both of them with .NET clients. What I have tried 0. Setting up the environment I have installed the SSLCACertificates (on root and two intermediate) and the client certificate in my local machine (win 7 professional) using certmgr.exe. 1. For the web service I have the client certificate (der). The service will be consumed via a .NET proxy. Here's the code: OrderWSService proxy = new OrderWSService(); string CertFile = "ClientCert_DER.cer"; proxy.ClientCertificates.Add(new System.Security.Cryptography.X509Certificates.X509Certificate(CertFile)); orderTrackingTO ot = new orderTrackingTO() { order_id = "80", tracking_id = "82", status = stateOrderType.IN_PREPARATION }; resultResponseTO res = proxy.insertOrderTracking(ot); Exception reported at last statement: The request failed with an empty response. 2. For the HTTP interface it is a HTTPS interface I have to call through POST method. The HTTPS request will be send from a .NET client using HTTPWebRequest. Here's the code: string PostData = "MyPostData"; //setting the request HttpWebRequest req; req = (HttpWebRequest)HttpWebRequest.Create(url); req.UserAgent = "MyUserAgent"; req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; req.ClientCertificates.Add(new System.Security.Cryptography.X509Certificates.X509Certificate(CertFile, "MyPassword")); //setting the request content byte[] byteArray = Encoding.UTF8.GetBytes(PostData); Stream dataStream = req.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); //obtaining the response WebResponse res = req.GetResponse(); r = new StreamReader(res.GetResponseStream()); Exception reported at last statement: The request was aborted: Could not create SSL/TLS secure channel. 3. Last try: using the browser In Chrome, after installing the certificates, if I try to access both urls I get a 107 error: Error 107 (net::ERR_SSL_PROTOCOL_ERROR) I am stuck.

    Read the article

  • Problem Executing Async Web Request

    - by davidhayes
    Hi Can anyone tell me what I've done wrong with this simple code? When I run it it hangs on using (Stream postStream = request.EndGetRequestStream(asynchronousResult)) If I comment out the requestState.Wait.WaitOne(); line the code executes correctly but obviously doesn't wait for the response. I'm guessing the the call to EndGetRequestStream is somehow returning me to the context of the main thread?? I'm pretty sure my code is essentially the same as the sample though (MSDN Documentation) using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.IO; using System.Text; namespace SBRemoteClient { public class JSONClient { public string ExecuteJSONQuery(string url, string query) { System.Uri uri = new Uri(url); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.Method = "POST"; request.Accept = "application/json"; byte[] requestBytes = Encoding.UTF8.GetBytes(query); RequestState requestState = new RequestState(request, requestBytes); IAsyncResult resultRequest = request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), requestState); requestState.Wait.WaitOne(); IAsyncResult resultResponse = (IAsyncResult)request.BeginGetResponse(new AsyncCallback(GetResponseStreamCallback), requestState); requestState.Wait.WaitOne(); return requestState.Response; } private static void GetRequestStreamCallback(IAsyncResult asynchronousResult) { try { RequestState requestState = (RequestState)asynchronousResult.AsyncState; HttpWebRequest request = requestState.Request; using (Stream postStream = request.EndGetRequestStream(asynchronousResult)) { postStream.Write(requestState.RequestBytes, 0, requestState.RequestBytes.Length); } requestState.Wait.Set(); } catch (Exception e) { Console.Out.WriteLine(e); } } private static void GetResponseStreamCallback(IAsyncResult asynchronousResult) { RequestState requestState = (RequestState)asynchronousResult.AsyncState; HttpWebRequest request = requestState.Request; using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult)) { using (Stream responseStream = response.GetResponseStream()) { using (StreamReader streamRead = new StreamReader(responseStream)) { requestState.Response = streamRead.ReadToEnd(); requestState.Wait.Set(); } } } } } }

    Read the article

  • WebClient and Gzip compression is faster?

    - by Yozer
    I writting an application which is using WebClient class. Adding something like that: ExC.Headers.Add("Accept-Encoding: gzip, deflate"); where ExC is: class ExWebClient1 : WebClient { protected override WebRequest GetWebRequest(Uri address) { HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address); request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; return request; } } It will be a diffrence in speed when i will be using encoded response?

    Read the article

  • System.Net.WebException: The remote server returned an error: (405) Method Not Allowed .exception occurred during the execution of the web request

    - by user88
    When I ran my web application code I got this error on this line. using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()){} Actually when I ran my url directly on browser.It will give proper o/p but when I ran my url in code. It will give exception. Here MyCode is :- string service = "http://api.ean.com/ean-services/rs/hotel/"; string version = "v3/"; string method = "info/"; string hotelId1 = "188603"; int hotelId = Convert.ToInt32(hotelId1); string otherElemntsStr = "&cid=411931&minorRev=[12]&customerUserAgent=[hotel]&locale=en_US&currencyCode=INR"; string apiKey = "tzyw4x2zspckjayrbjekb397"; string sig = "a6f828b696ae6a9f7c742b34538259b0"; string url = service + version + method + "?&type=xml" + "&apiKey=" + apiKey + "&sig=" + sig + otherElemntsStr + "&hotelId=" + hotelId; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url) as HttpWebRequest; request.Method = "POST"; request.ContentType = "text/xml"; request.ContentLength = 0; XmlDocument xmldoc = new XmlDocument(); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { StreamReader responsereader = new StreamReader(response.GetResponseStream()); var responsedata = responsereader.ReadToEnd(); xmldoc = (XmlDocument)JsonConvert.DeserializeXmlNode(responsedata); xmldoc.Save(@"D:\FlightSearch\myfile.xml"); xmldoc.Load(@"D:\FlightSearch\myfile.xml"); DataSet ds = new DataSet(); ds.ReadXml(Request.PhysicalApplicationPath + "myfile.xml"); GridView1.DataSource = ds.Tables["HotelSummary"]; GridView1.DataBind(); }

    Read the article

  • HttpRequest.BeginWebRequest not executing asynchronously

    - by Shawn Simon
    I have the following code: Private Function CreateRequest() As HttpWebRequest Dim request As HttpWebRequest = HttpWebRequest.Create(_url) request.Method = "POST" request.ContentType = "application/x-www-form-urlencoded" Dim postData As String = String.Join("&", GetPostData().Select(Function(s) String.Format("{0}={1}", s.Key, HttpUtility.UrlEncode(s.Value))).ToArray) Dim data As Byte() = (New ASCIIEncoding).GetBytes(postData) request.Timeout = _maxTimeoutSeconds * 1000 Dim stream = request.GetRequestStream stream.Write(data, 0, data.Length) stream.Close() Return request End Function Public Sub SendAsync(ByVal callback As Action(Of ResponseBase)) Dim request = CreateRequest() _attemptCount += 1 Dim reqID As Integer If _loggingContext IsNot Nothing Then Try reqID = Log.NotesRequest(_url.ToString, GetPostData, _loggingContext) Catch ex As Exception ErrorTracker.LogError(ex) End Try End If Dim responseState As New ResponseState responseState.LoggedNotesRequestID = reqID responseState.Request = request responseState.Callback = callback Dim response = request.BeginGetResponse(New AsyncCallback(AddressOf RespCallback), responseState) End Sub Private Sub RespCallback(ByVal ar As IAsyncResult) Dim responseState As ResponseState = CType(ar.AsyncState, ResponseState) ' Process response... I set up the request to go to a mock server which sleeps for 30 seconds. When I call BeginGetResponse, the application just waits at that line of code for the response. I want it to carry on with the app, and then just run the callback whenever it finishes. This code is run from a web page, and my callback just logs the response and sends an email. I don't want to use to have to wait for the response.

    Read the article

  • ExpertPDF and Caching of URLs

    - by Josh
    We are using ExpertPDF to take URLs and turn them into PDFs. Everything we do is through memory, so we build up the request and then read the stream into ExpertPDF and then write the bits to file. All the files we have been requesting so far are just plain HTML documents. Our designers update CSS files or change the HTML and rerequest the documents as PDFs, but often times, things are getting cached. Take, for example, if I rename the only CSS file and view the HTML page through a web browser, the page looks broke because the CSS doesn't exist. But if I request that page through the PDF Generator, it still looks ok, which means somewhere the CSS is cached. Here's the relevant PDF creation code: // Create a request HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.UserAgent = "IE 8.0"; request.ContentType = "application/x-www-form-urlencoded"; request.Method = "GET"; // Send the request HttpWebResponse resp = (HttpWebResponse)request.GetResponse(); if (resp.IsFromCache) { System.Web.HttpContext.Current.Trace.Write("FROM THE CACHE!!!"); } else { System.Web.HttpContext.Current.Trace.Write("not from cache"); } // Read the response pdf.SavePdfFromHtmlStream(resp.GetResponseStream(), System.Text.Encoding.UTF8, "Output.pdf"); When I check the trace file, nothing is being loaded from cache. I checked the IIS log file and found a 200 response coming from the request, even after a file had been updated (I would expect a 302). We've tried putting the No-Cache attribute on all HTML pages, but still no luck. I even turned off all caching at the IIS level. Is there anything in ExpertPDF that might be caching somewhere or something I can do to the request object to do a hard refresh of all resources? UPDATE I put ?foo at the end of my style href links and this updates the CSS everytime. Is there a setting someplace that can prevent stylesheets from being cached so I don't have to do this inelegant solution?

    Read the article

  • HttpWebResonse hangs on multiple request

    - by Ehsan
    I've an application that create many web request to donwload the news pages of a web site (i've tested for many web sites) after a while I find out that the application slows down in fetching the html source then I found out that HttpWebResonse fails getting the response. I post only the function that do this job. public PageFetchResult Fetch() { PageFetchResult fetchResult = new PageFetchResult(); try { HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(URLAddress); HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); Uri requestedURI = new Uri(URLAddress); Uri responseURI = resp.ResponseUri; if (Uri.Equals(requestedURI, responseURI)) { string resultHTML = ""; byte[] reqHTML = ResponseAsBytes(resp); if (!string.IsNullOrEmpty(FetchingEncoding)) resultHTML = Encoding.GetEncoding(FetchingEncoding).GetString(reqHTML); else if (!string.IsNullOrEmpty(resp.CharacterSet)) resultHTML = Encoding.GetEncoding(resp.CharacterSet).GetString(reqHTML); resp.Close(); fetchResult.IsOK = true; fetchResult.ResultHTML = resultHTML; } else { URLAddress = responseURI.AbsoluteUri; relayPageCount++; if (relayPageCount > 5) { fetchResult.IsOK = false; fetchResult.ErrorMessage = "Maximum page redirection occured."; return fetchResult; } return Fetch(); } } catch (Exception ex) { fetchResult.IsOK = false; fetchResult.ErrorMessage = ex.Message; } return fetchResult; } any solution would greatly appreciate

    Read the article

  • Mono Text Based Web Browser

    - by powerbox
    Hi guys, is there any public text based web browser implementation for C# or on mono base api that I can use to fill up web forms automatically? I'll be using it to automate some web task that does not require any image authentication. I'm currently using a web browser control available on .Net Framework and waits for the event WebBrowserDocumentCompletedEventHandler to fire after a page is successfully loaded and invoke some actions like Submit or simulating a mouse click on some links. It actually does the job but I can't process bulk transactions since I needed to wait for the whole page to be loaded together with the images and other stuff. It is easy to use HttpWebRequest to fill up some forms , provide some data and then submit. But on some occasions I only need to simulate a mouse click to a certain link which I don't know how to do with HttpWebRequest. By the way using HttpWebRequest will still download all the images of a web page that I see pointless since I only need to provide correct data back to the server. I hope someone can pinpoint me the correct way of doing this kind of automation and thanks in advance!

    Read the article

  • Twitter API Voting System

    - by Richard Jones
    So I blatantly got this idea from the MIX 10 event. At MIX they held a rockband talent competition type thing (I’m not quite sure of all the details).    But the interesting part for me is how they collected votes. They used Twitter (what else, when you have a few thousand geeks available to you). The basic idea was that you tweeted your vote with a # tag, i.e #ROCKBANDVOTE vote Richard How cool….    So the question is how do you write something to collate and count all the votes?   Time to press the magic Visual Studio new Project button… Twitter has a really nice API that can be invoked from .NET.   This is the snippet of code that will search for any given phrase i.e #ROCKBANDVOTE   public static XmlDocument GetSearchResults(string searchfor) { return GetSearchResults(searchfor, ""); }   public static XmlDocument GetSearchResults(string searchfor, string sinceid) { XmlDocument retdoc = new XmlDocument();   try { string url = "http://search.twitter.com/search.atom?&q=" + searchfor; if (sinceid.Length > 0) url += "since_id=" + sinceid; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; WebResponse res = request.GetResponse(); retdoc.Load(res.GetResponseStream()); res.Close();   } catch { } return retdoc; } } I’ve got two overloads, that optionally let you pass in the last ID to look for as well as what you want to search for. Note that Twitter rate limits the amount of requests you can send,  see http://apiwiki.twitter.com/Rate-limiting So realistically I wanted my app to run every hour or so and only pull out results that haven’t been received before (hence the overload to pass in the sinceid parameter). I’ll post the code when finished that parses the returned XML.

    Read the article

  • Get Asynchronous HttpResponse through Silverlight (F#)

    - by jack2010
    I am a newbie with F# and SL and playing with getting asynchronous HttpResponse through Silverlight. The following is the F# code pieces, which is tested on VS2010 and Window7 and works well, but the improvement is necessary. Any advices and discussion, especially the callback part, are welcome and great thanks. module JSONExample open System open System.IO open System.Net open System.Text open System.Web open System.Security.Authentication open System.Runtime.Serialization [<DataContract>] type Result<'TResult> = { [<field: DataMember(Name="code") >] Code:string [<field: DataMember(Name="result") >] Result:'TResult array [<field: DataMember(Name="message") >] Message:string } // The elements in the list [<DataContract>] type ChemicalElement = { [<field: DataMember(Name="name") >] Name:string [<field: DataMember(Name="boiling_point") >] BoilingPoint:string [<field: DataMember(Name="atomic_mass") >] AtomicMass:string } //http://blogs.msdn.com/b/dsyme/archive/2007/10/11/introducing-f-asynchronous-workflows.aspx //http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!194.entry type System.Net.HttpWebRequest with member x.GetResponseAsync() = Async.FromBeginEnd(x.BeginGetResponse, x.EndGetResponse) type RequestState () = let mutable request : WebRequest = null let mutable response : WebResponse = null let mutable responseStream : Stream = null member this.Request with get() = request and set v = request <- v member this.Response with get() = response and set v = response <- v member this.ResponseStream with get() = responseStream and set v = responseStream <- v let allDone = new System.Threading.ManualResetEvent(false) let getHttpWebRequest (query:string) = let query = query.Replace("'","\"") let queryUrl = sprintf "http://api.freebase.com/api/service/mqlread?query=%s" "{\"query\":"+query+"}" let request : HttpWebRequest = downcast WebRequest.Create(queryUrl) request.Method <- "GET" request.ContentType <- "application/x-www-form-urlencoded" request let GetAsynResp (request : HttpWebRequest) (callback: AsyncCallback) = let myRequestState = new RequestState() myRequestState.Request <- request let asyncResult = request.BeginGetResponse(callback, myRequestState) () // easy way to get it to run syncrnously w/ the asynch methods let GetSynResp (request : HttpWebRequest) : HttpWebResponse = let response = request.GetResponseAsync() |> Async.RunSynchronously downcast response let RespCallback (finish: Stream -> _) (asynchronousResult : IAsyncResult) = try let myRequestState : RequestState = downcast asynchronousResult.AsyncState let myWebRequest1 : WebRequest = myRequestState.Request myRequestState.Response <- myWebRequest1.EndGetResponse(asynchronousResult) let responseStream = myRequestState.Response.GetResponseStream() myRequestState.ResponseStream <- responseStream finish responseStream myRequestState.Response.Close() () with | :? WebException as e -> printfn "WebException raised!" printfn "\n%s" e.Message printfn "\n%s" (e.Status.ToString()) () | _ as e -> printfn "Exception raised!" printfn "Source : %s" e.Source printfn "Message : %s" e.Message () let printResults (stream: Stream)= let result = try use reader = new StreamReader(stream) reader.ReadToEnd(); finally () let data = Encoding.Unicode.GetBytes(result); let stream = new MemoryStream() stream.Write(data, 0, data.Length); stream.Position <- 0L let JsonSerializer = Json.DataContractJsonSerializer(typeof<Result<ChemicalElement>>) let result = JsonSerializer.ReadObject(stream) :?> Result<ChemicalElement> if result.Code<>"/api/status/ok" then raise (InvalidOperationException(result.Message)) else result.Result |> Array.iter(fun element->printfn "%A" element) let test = // Call Query (w/ generics telling it you wand an array of ChemicalElement back, the query string is wackyJSON too –I didn’t build it don’t ask me! let request = getHttpWebRequest "[{'type':'/chemistry/chemical_element','name':null,'boiling_point':null,'atomic_mass':null}]" //let response = GetSynResp request let response = GetAsynResp request (AsyncCallback (RespCallback printResults)) () ignore(test) System.Console.ReadLine() |> ignore

    Read the article

  • Why does IHttpAsyncHandler leak memory under load?

    - by Anton
    I have noticed that the .NET IHttpAsyncHandler (and the IHttpHandler, to a lesser degree) leak memory when subjected to concurrent web requests. In my tests, the development web server (Cassini) jumps from 6MB memory to over 100MB, and once the test is finished, none of it is reclaimed. The problem can be reproduced easily. Create a new solution (LeakyHandler) with two projects: An ASP.NET web application (LeakyHandler.WebApp) A Console application (LeakyHandler.ConsoleApp) In LeakyHandler.WebApp: Create a class called TestHandler that implements IHttpAsyncHandler. In the request processing, do a brief Sleep and end the response. Add the HTTP handler to Web.config as test.ashx. In LeakyHandler.ConsoleApp: Generate a large number of HttpWebRequests to test.ashx and execute them asynchronously. As the number of HttpWebRequests (sampleSize) is increased, the memory leak is made more and more apparent. LeakyHandler.WebApp TestHandler.cs namespace LeakyHandler.WebApp { public class TestHandler : IHttpAsyncHandler { #region IHttpAsyncHandler Members private ProcessRequestDelegate Delegate { get; set; } public delegate void ProcessRequestDelegate(HttpContext context); public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData) { Delegate = ProcessRequest; return Delegate.BeginInvoke(context, cb, extraData); } public void EndProcessRequest(IAsyncResult result) { Delegate.EndInvoke(result); } #endregion #region IHttpHandler Members public bool IsReusable { get { return true; } } public void ProcessRequest(HttpContext context) { Thread.Sleep(10); context.Response.End(); } #endregion } } LeakyHandler.WebApp Web.config <?xml version="1.0"?> <configuration> <system.web> <compilation debug="false" /> <httpHandlers> <add verb="POST" path="test.ashx" type="LeakyHandler.WebApp.TestHandler" /> </httpHandlers> </system.web> </configuration> LeakyHandler.ConsoleApp Program.cs namespace LeakyHandler.ConsoleApp { class Program { private static int sampleSize = 10000; private static int startedCount = 0; private static int completedCount = 0; static void Main(string[] args) { Console.WriteLine("Press any key to start."); Console.ReadKey(); string url = "http://localhost:3000/test.ashx"; for (int i = 0; i < sampleSize; i++) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.BeginGetResponse(GetResponseCallback, request); Console.WriteLine("S: " + Interlocked.Increment(ref startedCount)); } Console.ReadKey(); } static void GetResponseCallback(IAsyncResult result) { HttpWebRequest request = (HttpWebRequest)result.AsyncState; HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result); try { using (Stream stream = response.GetResponseStream()) { using (StreamReader streamReader = new StreamReader(stream)) { streamReader.ReadToEnd(); System.Console.WriteLine("C: " + Interlocked.Increment(ref completedCount)); } } response.Close(); } catch (Exception ex) { System.Console.WriteLine("Error processing response: " + ex.Message); } } } }

    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

  • HTTP Protocal

    I have worked with the HTTP protocal for about ten years now and I have found it to be incredibly usefull for transfering data espicaly for remote systems and regardless of the network enviroment. Prior to the existance of web services, developers use to use HTTP to screen scrap data off of web pages in order to interact with remote systems, and then process the data as they needed. I use to use the HTTPWebRequest and HTTPWebRespones classes in order to screen scrap data from various sites that had information I needed to use if no web service was avalible. This allowed me to call just about any webpage and grab all of the content on the page. Below is piece of a web spider that I build about 5-7 years ago. The spider uses the HTTP protocal to requst webpages and then parse the data that is returned.  At the time of writing the spider I wanted to create a searchable index of sites I frequented. // C# 2.0 Framework// Creating a request for a specfic webpageHttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(_Url); // Storeing the response of the webrequestwebresp = (HttpWebResponse)webreq.GetResponse(); StreamReader loResponseStream = new StreamReader(webresp.GetResponseStream()); _Content = loResponseStream.ReadToEnd(); // Adjust the Encoding of Responsestring charset = "";EncodeString(ref _Content, ref charset);loResponseStream.Close(); //Parse Data from the Respone_Content = _Content.Replace("\n", "");_Head = GetTagByName("Head", _Content);_Title = GetTagByName("title", _Content);_Body = GetTagByName("body", _Content);

    Read the article

  • System.Net.WebException: Unable to connect to the remote server

    - by Anilkumar
    System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) at System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP) at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception) --- End of inner exception stack trace --- at System.Net.HttpWebRequest.GetRequestStream() at OmnexCRMFileDownloader.OmnCRMTemplateDataReader.GetProposalData(String lurl) I'm getting the above error when I try to post to a .aspx page.I think it is not Posting to the page I specified. HttpWebRequest.GetRequestStream() is not getting as expected. Pls help.

    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

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >