Search Results

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

Page 3/19 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • HttpWebRequest to different IP than the domain resolves to

    - by fyjham
    Hey, Long story short an API I'm calling's different environments (dev/staging/uat/live) is set up by putting a host-record on the server so the live domain resolves to their other server in for the HTTP request. The problem is that they've done this with so many different environments that we don't have enough servers to use the server-wide host files for it anymore (We've got some environments running off the same servers - luckily not dev and live though :P). I'm wondering if there's a way to make WebRequest request to a domain but explicitly specify the IP of the server it should connect to? Or is there any way of doing this short of going all the way down to socket connections (Which I'd really prefer not to waste time/create bugs by trying to re-implementing the HTTP protocol). PS: I've tried and we can't just get a new sub-domain for each environment.

    Read the article

  • How to SetCookie() in a System.Net.HttpWebRequest request for another Page2.aspx?

    - by Mike108
    How can I SetCookie in Page1.aspx by a System.Net.HttpWebRequest request for Page2.aspx which handle the SetCookie() function? Page1.aspx and Page2.aspx are in the same webapp. Page1.aspx: protected void Page_Load(object sender, EventArgs e) { string url = "http://localhost/Page2.aspx"; System.Net.HttpWebRequest myReq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url); System.Net.HttpWebResponse HttpWResp = (System.Net.HttpWebResponse)myReq.GetResponse(); System.IO.Stream myStream = HttpWResp.GetResponseStream(); } Page2.aspx: protected void Page_Load(object sender, EventArgs e) { string userName = "Lily"; FormsAuthentication.SetAuthCookie(userName, true); }

    Read the article

  • How to force HttpWebRequest to use cache in ASP.NET environment?

    - by piotrsz
    In my ASP.NET app I use HttpWebRequest for fetching external resources which I'd like to be cached. Consider the following code: var req = WebRequest.Create("http://google.com/"); req.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.CacheIfAvailable); var resp = req.GetResponse(); Console.WriteLine(resp.IsFromCache); var answ = (new StreamReader(resp.GetResponseStream())).ReadToEnd(); Console.WriteLine(answ.Length); HttpWebRequest uses IE cache, so when I run it as normal user, data is cached to %userprofile%\Local Settings\Temporary Internet Files and next responses are read from cache. I thought that when such code is run inside ASP.NET app, data will be cached to ...\ASPNET\Local Settings\Temporary Internet Files but it is not and cache is never used. What I am doing wrong? How to force HttpWebRequest to use cache in ASP.NET environment?

    Read the article

  • how to read httpWebRequest's request stream in c#, i got error" the stream is not readable" ?

    - by sam
    hi i want to read request stream from a custom httpWebRequest class that inherits from httpWebRequest and i have tried to read the request stream in different stages but sitll not sure how to archieve that in the class,thanks very much for any help. This custom httpWebRequest is used to serilize soap message and i want to know what request has been sent in string format. I also implemented custom HttpRequestCreator,HttpWebResponse but till cant find a place/stage i can read the request stream. If i output everything in a memory stream then copy the content to request stream, anyone knows which stage i can do it in the constructor, BeginGetRequestStream,EndGetRequestStream or GetRequestStream?

    Read the article

  • Getting Http Status code number (200, 301, 404, etc.) from HttpWebRequest and HttpWebResponse

    - by James Lawruk
    I am trying to get the HTTP status code number from the HttpWebResponse object returned from a HttpWebRequest. I was hoping to get the actual numbers (200, 301,302, 404, etc.) rather than the text description. ("Ok", "MovedPermanently", etc.) Is the number buried in a property somewhere in the response object? Any ideas other than creating a big switch function? Thanks. HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://www.gooogle.com/"); webRequest.AllowAutoRedirect = false; HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse(); //Returns "MovedPermanently", not 301 which is what I want. Console.Write(response.StatusCode.ToString());

    Read the article

  • Writing file from HttpWebRequest periodically vs. after download finishes?

    - by WB3000
    Right now I am using this code to download files (with a Range header). Most of the files are large, and it is running 99% of CPU currently as the file downloads. Is there any way that the file can be written periodically so that it does not remain in RAM constantly? private byte[] GetWebPageContent(string url, long start, long finish) { byte[] result = new byte[finish]; HttpWebRequest request; request = WebRequest.Create(url) as HttpWebRequest; //request.Headers.Add("Range", "bytes=" + start + "-" + finish); request.AddRange((int)start, (int)finish); using (WebResponse response = request.GetResponse()) { return ReadFully(response.GetResponseStream()); } } public static byte[] ReadFully(Stream stream) { byte[] buffer = new byte[32768]; using (MemoryStream ms = new MemoryStream()) { while (true) { int read = stream.Read(buffer, 0, buffer.Length); if (read <= 0) return ms.ToArray(); ms.Write(buffer, 0, read); } } }

    Read the article

  • HttpWebRequest response produces HTTP 422. Why?

    - by Simon
    Hi there. I'm trying to programmatically send a POST-request to a web-server in order to login an then perform other requests that require a login. This is my code: Encoding.UTF8.GetBytes( String.Format( "login={0}&password={1}&authenticity_token={2}", username, password, token)); //Create HTTP-request for login HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://www.xxx.xx/xx/xx"); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; request.CookieContainer = new CookieContainer(); request.Accept = "application/xml,application/xhtml+xml,text/html; +"q=0.9,text/plain ;q=0.8,image/png,*/*;q=0.5"; request.Referer = "http://www.garzantilinguistica.it/it/session"; request.Headers.Add("Accept-Language", "de-DE"); request.Headers.Add("Origin", "http://www.xxx.xx"); request.UserAgent = "C#"; request.Headers.Add("Accept-Encoding", "gzip, deflate"); After sending the request //Send post request var requestStream = request.GetRequestStream(); requestStream.Write(data, 0, data.Length); requestStream.Flush(); requestStream.Close(); ... I want to get the servers response: //Get Response StreamReader responseStreamReader = new StreamReader( request.GetResponse().GetResponseStream()); //WebException: HTTP 422! string content = responseStreamReader.ReadToEnd(); This piece of code fires the WebException, that tells me the server responded with HTTP 422 (unprocessable entity due to semantic errors) Then I compared (using a TCP/IP sniffers) the requests of my program and the browser (which of course produces a valid POST-request and gets the right response). (1) My program's request: POST /it/session HTTP/1.1 Content-Type: application/x-www-form-urlencoded Accept: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain; q=0.8,image/png,*/*;q=0.5 Referer: http://www.garzantilinguistica.it/it/session Accept-Language: de-DE Origin: http://www.garzantilinguistica.it User-Agent: C# Accept-Encoding: gzip, deflate Host: www.garzantilinguistica.it Content-Length: 111 Expect: 100-continue Connection: Keep-Alive HTTP/1.1 100 Continue [email protected]&password=machivui&authenticity_token=4vLgtwP3nFNg4NeuG4MbUnU7sy4z91Wi8WJXH0POFmg= HTTP/1.1 422 Unprocessable Entity (2) The browser's request: POST /it/session HTTP/1.1 Host: www.garzantilinguistica.it Referer: http://www.garzantilinguistica.it/it/session Accept: application/xml,application/xhtml+xml,text/html;q=0.9, text/plain;q=0.8,image/png,*/*;q=0.5 Accept-Language: de-DE Origin: http://www.garzantilinguistica.it User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; de-DE) AppleWebKit/531.22.7 (KHTML, like Gecko) Version/4.0.5 Safari/531.22.7 Accept-Encoding: gzip, deflate Content-Type: application/x-www-form-urlencoded Cookie: __utma=244184339.652523587.1275208707.1275208707.1275211298.2; __utmb=244184339.20.10.1275211298; __utmc=244184339; __utmz=244184339.1275208707.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); _garzanti2009_session=BAh7CDoPc2Vzc2lvbl9pZCIlZDg4MWZjNjg2YTRhZWE0NDQ0ZTJmMTU2YWY4ZTQ1NGU6EF9jc3JmX3Rva2VuIjFqRWdLdll3dTYwOTVVTEpNZkt6dG9jUCtaZ0o4V0FnV2V5ZnpuREx6QUlZPSIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNoSGFzaHsGOgplcnJvciIVbG9naW4gbm9uIHZhbGlkbwY6CkB1c2VkewY7CFQ%3D--4200fa769898dd156faa49e457baf660cf068d08 Content-Length: 144 Connection: keep-alive authenticity_token=jEgKvYwu6095ULJMfKztocP%2BZgJ8WAgWeyfznDLzAIY%3D&login=thespider14%40hotmail.com&password=machivui&remember_me=1&commit=Entra HTTP/1.1 302 Found Can someone help to understand which part of the request I am missing or what the main difference between the browser's and my request is? Why am I getting that 422?

    Read the article

  • Async WebRequest Timeout Windows Phone 7

    - by Tyler
    Hi All, I'm wondering what the "right" way of timing out an HttpWebRequest is on Windows Phone7? I've been reading about ThreadPool.RegisterWaitForSingleObject() but this can't be used as WaitHandles throw a Not implemented exception at run time. I've also been looking at ManualReset events but A) Don't understand them properly and B) Don't understand how blocking the calling thread is an acceptable way to implement a time out on an Async request. Here's my existing code sans timeout, can someone please show me how I would add a timeout to this? public static void Get(Uri requestUri, HttpResponseReceived httpResponseReceivedCallback, ICredentials credentials, object userState, bool getResponseAsString = true, bool getResponseAsBytes = false) { var httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri); httpWebRequest.Method = "GET"; httpWebRequest.Credentials = credentials; var httpClientRequestState = new JsonHttpClientRequestState(null, userState, httpResponseReceivedCallback, httpWebRequest, getResponseAsString, getResponseAsBytes); httpWebRequest.BeginGetResponse(ResponseReceived, httpClientRequestState); } private static void ResponseReceived(IAsyncResult asyncResult) { var httpClientRequestState = asyncResult.AsyncState as JsonHttpClientRequestState; Debug.Assert(httpClientRequestState != null, "httpClientRequestState cannot be null. Fatal error."); try { var webResponse = (HttpWebResponse)httpClientRequestState.HttpWebRequest.EndGetResponse(asyncResult); } }

    Read the article

  • How to use SSL3 instead of TLS in a particular HttpWebRequest?

    - by Anton Tykhyy
    My application has to talk to different hosts over https, and the default setting of ServicePointManager.SecurityProtocol = TLS served me well up to this day. Now I have some hosts which (as System.Net trace log shows) don't answer the initial TLS handshake message but keep the underlying connection open until it times out, throwing a timeout exception. I tried setting HttpWebRequest's timeout to as much as 5mins, with the same result. Presumably these hosts are waiting for an SSL3 handshake since both IE and Firefox are able to connect to these hosts after a 30-40 seconds' delay. There seems to be some fallback mechanism in .NET which degrades TLS to SSL3, but it doesn't kick in for some reason. FWIW, here's the handshake message my request is sending: 00000000 : 16 03 01 00 57 01 00 00-53 03 01 4C 12 39 B4 F9 : ....W...S..L.9.. 00000010 : A3 2C 3D EE E1 2A 7A 3E-D2 D6 0D 2E A9 A8 6C 03 : .,=..*z>......l. 00000020 : E7 8F A3 43 0A 73 9C CE-D7 EE CF 00 00 18 00 2F : ...C.s........./ 00000030 : 00 35 00 05 00 0A C0 09-C0 0A C0 13 C0 14 00 32 : .5.............2 00000040 : 00 38 00 13 00 04 01 00-00 12 00 0A 00 08 00 06 : .8.............. 00000050 : 00 17 00 18 00 19 00 0B-00 02 01 00 : ............ Is there a way to use SSL3 instead of TLS in a particular HttpWebRequest, or force a fallback? It seems that ServicePointManager's setting is global, and I'd really hate to have to degrade the security protocol setting to SSL3 for the whole application.

    Read the article

  • Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

    - by Greg
    Hi, Any ideas why on some links that I try to access using HttpWebRequest I am getting "The remote server returned an error: (304) Not Modified." in the code? The code I'm using is from Jeff's post here. Note the concept of the code is a simple proxy server, so I'm pointing my browser at this locally running piece of code, which gets my browsers request, and then proxies it on by creating a new HttpWebRequest, as you'll see in the code. It works great for most sites/links, but for some this error comes up. You will see one key bit in the code is where it seems to copy the http header settings from the browser request to it's request out to the site, and it copies in the header attributes. Not sure if the issue is something to do with how it mimics this aspect of the request and then what happens as the result comes back? case "If-Modified-Since": request.IfModifiedSince = DateTime.Parse(listenerContext.Request.Headers[key]); break; I get the issue for example from http://en.wikipedia.org/wiki/Main_Page thanks

    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

  • HttpWebRequest and Ignoring SSL Certificate Errors

    - by Rick Strahl
    Man I can't believe this. I'm still mucking around with OFX servers and it drives me absolutely crazy how some these servers are just so unbelievably misconfigured. I've recently hit three different 3 major brokerages which fail HTTP validation with bad or corrupt certificates at least according to the .NET WebRequest class. What's somewhat odd here though is that WinInet seems to find no issue with these servers - it's only .NET's Http client that's ultra finicky. So the question then becomes how do you tell HttpWebRequest to ignore certificate errors? In WinInet there used to be a host of flags to do this, but it's not quite so easy with WebRequest. Basically you need to configure the CertificatePolicy on the ServicePointManager by creating a custom policy. Not exactly trivial. Here's the code to hook it up: public bool CreateWebRequestObject(string Url) {    try     {        this.WebRequest =  (HttpWebRequest) System.Net.WebRequest.Create(Url);         if (this.IgnoreCertificateErrors)            ServicePointManager.CertificatePolicy = delegate { return true; };}One thing to watch out for is that this an application global setting. There's one global ServicePointManager and once you set this value any subsequent requests will inherit this policy as well, which may or may not be what you want. So it's probably a good idea to set the policy when the app starts and leave it be - otherwise you may run into odd behavior in some situations especially in multi-thread situations.Another way to deal with this is in you application .config file. Normal 0 false false false EN-US X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin-top:0in; mso-para-margin-right:0in; mso-para-margin-bottom:10.0pt; mso-para-margin-left:0in; line-height:115%; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi;} <configuration>   <system.net>     <settings>       <servicePointManager           checkCertificateName="false"           checkCertificateRevocationList="false"                />     </settings>   </system.net> </configuration> This seems to work most of the time, although I've seen some situations where it doesn't, but where the code implementation works which is frustrating. The .config settings aren't as inclusive as the programmatic code that can ignore any and all cert errors - shrug. Anyway, the code approach got me past the stopper issue. It still amazes me that theses OFX servers even require this. After all this is financial data we're talking about here. The last thing I want to do is disable extra checks on the certificates. Well I guess I shouldn't be surprised - these are the same companies that apparently don't believe in XML enough to generate valid XML (or even valid SGML for that matter)...© Rick Strahl, West Wind Technologies, 2005-2011Posted in .NET  CSharp  HTTP  

    Read the article

  • Using the HttpWebRequest class.

    - by Nick
    I instantiate the HttpWebRequest object: HttpWebRequest httpWebRequest = WebRequest.Create("http://game.stop.com/webservice/services/gameup") as HttpWebRequest; When I "post" the data to this service, how does the service know which web method to submit the data to? I do not have the code to this web service, all I know is that it was written in Java.

    Read the article

  • HttpWebRequest.GetResponse() - what specific status codes cause an exception to be thrown?

    - by H. Morrow
    I've hunted around for some definitive documentation on this but haven't had much luck finding any. Basically - the question is - for which HTTP Status codes coming back from the server will HttpWebRequest.GetResponse() generate a WebException after doing something like say, a POST? Specifically - will it generate a WebException for anything other than status 200 OK? Or will it only generate a WebException for say, 400, 404, and 500 (for the sake of argument). I want to know since, the server I'm communicating with defines anything other than HTTP 200 OK coming back as an error condition - and the key is, can I rely on a WebException being generated for anything other than 200? (I've currently written my code so that it'll actually check the return status code everytime to ensure it's 200 OK and if it's not, take appropriate action - but it's alot of duplication between that, and the catch block for a WebException, and I'm hoping to clean it up...) Any relevant links to documentation would be most appreciated. Thanks!

    Read the article

  • HttpWebRequest: The request was aborted: The request was canceled.

    - by Emeka
    I've been working on developing a middle man application of sorts, which uploads text to a CMS backend using HTTP post requests for a series of dates (usually 7 at a time). I am using HttpWebRequest to accomplish this. It seems to work fine for the first date, but when it starts the second date I get the System.Net.WebException: The request was aborted: The request was canceled. I've searched around and found the following big clues: http://social.msdn.microsoft.com/Forums/en-US/netfxnetcom/thread/0d0afe40-c62a-4089-9d8b-fb4d206434dc http://www.jaxidian.org/update/2007/05/05/8 http://arnosoftwaredev.blogspot.com/2006/09/net-20-httpwebrequestkeepalive-and.html And they haven't been too helpful. I've tried overloading the GetWebReuqest but that doesn't make sense because I don't make any use of that function. Here is my code: http://pastebin.org/115268 I get the error on line 245 after it has run successfully at least once. I'd appreciate any help I can get as this is the last step in a project I've been working on for sometime. This is my first C#/VS project so I'm open to any tips but I would like to focus on getting this problem solved first. THanks!

    Read the article

  • Call HttpWebRequest in another thread as UI with Task class - avoid to dispose object created in Task scope

    - by John
    I would like call HttpWebRequest on another thread as UI, because I must make 200 request or server and downloaded image. My scenation is that I make a request on server, create image and return image. This I make in another thread. I use Task class, but it call automaticaly Dispose method on all object created in task scope. So I return null object from this method. public BitmapImage CreateAvatar(Uri imageUri, int sex) { if (imageUri == null) return CreateDefaultAvatar(sex); BitmapImage image = null; new Task(() => { var request = WebRequest.Create(imageUri); var response = request.GetResponse(); using (var stream = response.GetResponseStream()) { Byte[] buffer = new Byte[response.ContentLength]; int offset = 0, actuallyRead = 0; do { actuallyRead = stream.Read(buffer, offset, buffer.Length - offset); offset += actuallyRead; } while (actuallyRead > 0); image = new BitmapImage { CreateOptions = BitmapCreateOptions.None, CacheOption = BitmapCacheOption.OnLoad }; image.BeginInit(); image.StreamSource = new MemoryStream(buffer); image.EndInit(); image.Freeze(); } }).Start(); return image; } How avoid it? Thank Mr. Jon Skeet try this: private Stream GetImageStream(Uri imageUri) { Byte[] buffer = null; //new Task(() => //{ var request = WebRequest.Create(imageUri); var response = request.GetResponse(); using (var stream = response.GetResponseStream()) { buffer= new Byte[response.ContentLength]; int offset = 0, actuallyRead = 0; do { actuallyRead = stream.Read(buffer, offset, buffer.Length - offset); offset += actuallyRead; } while (actuallyRead > 0); } //}).Start(); return new MemoryStream(buffer); } It return object which is null a than try this: private Stream GetImageStream(Uri imageUri) { Byte[] buffer = null; new Task(() => { var request = WebRequest.Create(imageUri); var response = request.GetResponse(); using (var stream = response.GetResponseStream()) { buffer= new Byte[response.ContentLength]; int offset = 0, actuallyRead = 0; do { actuallyRead = stream.Read(buffer, offset, buffer.Length - offset); offset += actuallyRead; } while (actuallyRead > 0); } }).Start(); return new MemoryStream(buffer); } Method above return null

    Read the article

  • HttpWebRequest: How to find a postal code at Canada Post through a WebRequest with x-www-form-enclos

    - by Will Marcouiller
    I'm currently writing some tests so that I may improve my skills with the Internet interaction through Windows Forms. One of those tests is to find a postal code which should be returned by Canada Post website. My default URL setting is set to: http://www.canadapost.ca/cpotools/apps/fpc/personal/findByCity?execution=e4s1 The required form fields are: streetNumber, streetName, city, province The contentType is "application/x-www-form-enclosed" EDIT: Please consider the value "application/x-www-form-encoded" instead of point 3 value as the contentType. (Thanks EricLaw-MSFT!) The result I get is not the result expected. I get the HTML source code of the page where I could manually enter the information to find the postal code, but not the HTML source code with the found postal code. Any idea of what I'm doing wrong? Shall I consider going the XML way? Is it first of all possible to search on Canada Post anonymously? Here's a code sample for better description: public static string FindPostalCode(ICanadadianAddress address) { var postData = string.Concat(string.Format("&streetNumber={0}", address.StreetNumber) , string.Format("&streetName={0}", address.StreetName) , string.Format("&city={0}", address.City) , string.Format("&province={0}", address.Province)); var encoding = new ASCIIEncoding(); byte[] postDataBytes = encoding.GetBytes(postData); request = (HttpWebRequest)WebRequest.Create(DefaultUrlSettings); request.ImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Anonymous; request.Container = new CookieContainer(); request.Timeout = 10000; request.ContentType = contentType; request.ContentLength = postDataBytes.LongLength; request.Method = @"post"; var senderStream = new StreamWriter(request.GetRequestStream()); senderStream.Write(postDataBytes, 0, postDataBytes.Length); senderStream.Close(); string htmlResponse = new StreamReader(request.GetResponse().GetResponseStream()).ReadToEnd(); return processedResult(htmlResponse); // Processing the HTML source code parsing, etc. } I seem stuck in a bottle neck in my point of view. I find no way out to the desired result. EDIT: There seems to have to parameters as for the ContentType of this site. Let me explain. There's one with the "meta"-variables which stipulates the following: meta http-equiv="Content-Type" content="application/xhtml+xml, text/xml, text/html; charset=utf-8" And another one later down the code that is read as: form id="fpcByAdvancedSearch:fpcSearch" name="fpcByAdvancedSearch:fpcSearch" method="post" action="/cpotools/apps/fpc/personal/findByCity?execution=e1s1" enctype="application/x-www-form-urlencoded" My question is the following: With which one do I have to stick? Let me guess, the first ContentType is to be considered as the second is only for another request to a function or so when the data is posted? EDIT: As per request, the closer to the solution I am is listed under this question: WebRequest: How to find a postal code using a WebRequest against this ContentType=”application/xhtml+xml, text/xml, text/html; charset=utf-8”? Thanks for any help! :-)

    Read the article

  • C#: Cannot handle redirect from HTTP/HTTPS protocols to other dissimilar ones

    - by Peanut
    Basically, I'm trying to grab an EXE from CNet's Download.com So i created web parser and so far all is going well. Here is a sample link pulled directly from their site: http://dw.com.com/redir?edId=3&siteId=4&oId=3001-20_4-10308491&ontId=20_4&spi=e6323e8d83a8b4374d43d519f1bd6757&lop=txt&tag=idl2&pid=10566981&mfgId=6250549&merId=6250549&pguid=PlvcGQoPjAEAAH5rQL0AAABv&destUrl=ftp%3A%2F%2F202.190.201.108%2Fpub%2Fryl2%2Fclient%2Finstaller-ryl2_v1673.exe Here is the problem: When you attempt to download, it begins with HTTP, then redirects to an FTP site. I have tried .NET's WebClient and HttpWebRequest Objects, and it looks like Neither can support Redirects. This Code Fails at GetResponse(); HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://dw.com.com/redir?edId=3&siteId=4&oId=3001-20_4-10308491&ontId=20_4&spi=e6323e8d83a8b4374d43d519f1bd6757&lop=txt&tag=idl2&pid=10566981&mfgId=6250549&merId=6250549&pguid=PlvcGQoPjAEAAH5rQL0AAABv&destUrl=ftp%3A%2F%2F202.190.201.108%2Fpub%2Fryl2%2Fclient%2Finstaller-ryl2_v1673.exe"); WebResponse response = req.GetResponse(); Now, I also tried this: HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://dw.com.com/redir?edId=3&siteId=4&oId=3001-20_4-10308491&ontId=20_4&spi=e6323e8d83a8b4374d43d519f1bd6757&lop=txt&tag=idl2&pid=10566981&mfgId=6250549&merId=6250549&pguid=PlvcGQoPjAEAAH5rQL0AAABv&destUrl=ftp%3A%2F%2F202.190.201.108%2Fpub%2Fryl2%2Fclient%2Finstaller-ryl2_v1673.exe"); req.AllowAutoRedirect = false; WebResponse response = req.GetResponse(); string s = new StreamReader(response.GetResponseStream()).ReadToEnd(); And it does not throw the error anymore, however variable s turns out to be an empty string. I'm at a loss! Can anyone help out?

    Read the article

  • How to login to wordpress programmatically?

    - by T-Rex
    I need to perform some action in wordpress admin panel programmatically but can't manage how to login to Wordpress using C# and HttpWebRequest. Here is what I do: private void button1_Click(object sender, EventArgs e) { string url = "http://localhost/wordpress/wp-login.php"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); CookieContainer cookies = new CookieContainer(); SetupRequest(url, request, cookies); //request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; //request.Headers["Accept-Language"] = "uk,ru;q=0.8,en-us;q=0.5,en;q=0.3"; //request.Headers["Accept-Encoding"] = "gzip,deflate"; //request.Headers["Accept-Charset"] = "windows-1251,utf-8;q=0.7,*;q=0.7"; string user = "test"; string pwd = "test"; request.Credentials = new NetworkCredential(user, pwd); string data = string.Format( "log={0}&pwd={1}&wp-submit={2}&testcookie=1&redirect_to={3}", user, pwd, System.Web.HttpUtility.UrlEncode("Log In"), System.Web.HttpUtility.UrlEncode("http://localhost/wordpress/wp-admin/")); SetRequestData(request, data); ShowResponse(request); } private static void SetupRequest(string url, HttpWebRequest request, CookieContainer cookies) { request.CookieContainer = cookies; request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; uk; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)"; request.KeepAlive = true; request.Timeout = 120000; request.Method = "POST"; request.Referer = url; request.ContentType = "application/x-www-form-urlencoded"; } private void ShowResponse(HttpWebRequest request) { HttpWebResponse response = (HttpWebResponse)request.GetResponse(); responseTextBox.Text = (((HttpWebResponse)response).StatusDescription); responseTextBox.Text += "\r\n"; StreamReader reader = new StreamReader(response.GetResponseStream()); responseTextBox.Text += reader.ReadToEnd(); } private static void SetRequestData(HttpWebRequest request, string data) { byte[] streamData = Encoding.ASCII.GetBytes(data); request.ContentLength = streamData.Length; Stream dataStream = request.GetRequestStream(); dataStream.Write(streamData, 0, streamData.Length); dataStream.Close(); } But unfortunately in responce I get only HTML source code of login page and it seems that cookies don't contain session ID. All requests which I perform after that code also return HTML source of login page so I can assume that it does not login correctly. Can anybody help me to solve that problem or give working example? Main thing which I want to achieve is scanning for new images in Nextgen Gallery plugin for Wordpress. Is there XML-RPC way of doing that? Thanks in advance.

    Read the article

  • Help deciphering exception details from WebRequestCreator when setting ContentType to "application/json"

    - by Stephen Patten
    Hello, This one is real simple, run this Silverlight4 example with the ContentType property commented out and you'll get back a response from from my service in xml. Now uncomment the property and run it and you'll get an exception similar to this one. System.Net.ProtocolViolationException occurred Message=A request with this method cannot have a request body. StackTrace: at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state) at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult) at com.patten.silverlight.ViewModels.WebRequestLiteViewModel.<MakeCall>b__0(IAsyncResult cb) InnerException: What I am trying to accomplish is just pulling down some JSON formatted data from my wcf endpoint. Can this really be this hard, or is it another classic example of just overlooking something simple. Edit: While perusing SO, I noticed similar posts, like this one Why am I getting ProtocolViolationException when trying to use HttpWebRequest? Thank you, Stephen try { Address = "http://stephenpattenconsulting.com/Services/GetFoodDescriptionsLookup(2100)"; // Get the URI Uri httpSite = new Uri(Address); // Create the request object using the Browsers networking stack // HttpWebRequest wreq = (HttpWebRequest)WebRequest.Create(httpSite); // Create the request using the operating system's networking stack HttpWebRequest wreq = (HttpWebRequest)WebRequestCreator.ClientHttp.Create(httpSite); // http://stackoverflow.com/questions/239725/c-webrequest-class-and-headers // These headers have been set, so use the property that has been exposed to change them // wreq.Headers[HttpRequestHeader.ContentType] = "application/json"; //wreq.ContentType = "application/json"; // Issue the async request. // http://timheuer.com/blog/archive/2010/04/23/silverlight-authorization-header-access.aspx wreq.BeginGetResponse((cb) => { HttpWebRequest rq = cb.AsyncState as HttpWebRequest; HttpWebResponse resp = rq.EndGetResponse(cb) as HttpWebResponse; StreamReader rdr = new StreamReader(resp.GetResponseStream()); string result = rdr.ReadToEnd(); Jounce.Framework.JounceHelper.ExecuteOnUI(() => { Result = result; }); rdr.Close(); }, wreq); } catch (WebException ex) { Jounce.Framework.JounceHelper.ExecuteOnUI(() => { Error = ex.Message; }); } catch (Exception ex) { Jounce.Framework.JounceHelper.ExecuteOnUI(() => { Error = ex.Message; }); } EDIT: This is how the WCF 4 end point is configured, primarily 'adapted' from this link http://geekswithblogs.net/michelotti/archive/2010/08/21/restful-wcf-services-with-no-svc-file-and-no-config.aspx [ServiceContract] public interface IRDA { [OperationContract] IList<FoodDescriptionLookup> GetFoodDescriptionsLookup(String id); [OperationContract] FOOD_DES GetFoodDescription(String id); [OperationContract] FOOD_DES InsertFoodDescription(FOOD_DES foodDescription); [OperationContract] FOOD_DES UpdateFoodDescription(String id, FOOD_DES foodDescription); [OperationContract] void DeleteFoodDescription(String id); } // RESTfull service [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class RDAService : IRDA { [WebGet(UriTemplate = "FoodDescription({id})")] public FOOD_DES GetFoodDescription(String id) { ... } [AspNetCacheProfile("GetFoodDescriptionsLookup")] [WebGet(UriTemplate = "GetFoodDescriptionsLookup({id})")] public IList<FoodDescriptionLookup> GetFoodDescriptionsLookup(String id) { return rda.GetFoodDescriptionsLookup(id); ; } [WebInvoke(UriTemplate = "FoodDescription", Method = "POST")] public FOOD_DES InsertFoodDescription(FOOD_DES foodDescription) { ... } [WebInvoke(UriTemplate = "FoodDescription({id})", Method = "PUT")] public FOOD_DES UpdateFoodDescription(String id, FOOD_DES foodDescription) { ... } [WebInvoke(UriTemplate = "FoodDescription({id})", Method = "DELETE")] public void DeleteFoodDescription(String id) { ... } } And the portion of my web.config that pertains to WCF <system.serviceModel> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> <standardEndpoints> <webHttpEndpoint> <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" /> </webHttpEndpoint> </standardEndpoints> </system.serviceModel>

    Read the article

  • HttpWebRequest and BindIPEndPointDelegate getting socket exception

    - by Evgeny Gavrin
    I've got c# code running on a computer with multiple network interfaces, and the following code to select an IP address for a HttpWebRequest to bind ServicePoint: HttpWebRequest request = (HttpWebRequest)WebRequest.Create(remoteFilename); request.KeepAlive = false; request.ServicePoint.BindIPEndPointDelegate = delegate( ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount) { return new IPEndPoint(IPAddress.Parse(ipAddr), 0); }; But it works only for one of the available network interfaces. Trying to access remote server through others throws an exception: System.Net.WebException: Unable to connect to the remote server --- System.Net.Sockets.SocketException: A socket operation was attempted to an unreachable network How can it be solved?

    Read the article

  • Sending Client Certificate in HttpWebRequest

    - by Aaron Fischer
    I am trying to pass a client certificate to a server using the code below however I still revive the HTTP Error 403.7 - Forbidden: SSL client certificate is required. What are the possible reasons the HttpWebRequest would not send the client certificate? var clientCertificate = new X509Certificate2( @"C:\Development\TestClient.pfx", "bob" ); HttpWebRequest tRequest = ( HttpWebRequest )WebRequest.Create( "https://ofxtest.com/ofxr.dll" ); tRequest.ClientCertificates.Add( clientCertificate ); tRequest.PreAuthenticate = true; tRequest.KeepAlive = true; tRequest.Credentials = CredentialCache.DefaultCredentials; tRequest.Method = "POST"; var encoder = new ASCIIEncoding(); var requestData = encoder.GetBytes( "<OFX></OFX>" ); tRequest.GetRequestStream().Write( requestData, 0, requestData.Length ); tRequest.GetRequestStream().Close(); ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback( CertPolicy.ValidateServerCertificate ); WriteResponse( tRequest.GetResponse() );

    Read the article

  • TimeOuts with HttpWebRequest when running Selenium concurrently in .NET

    - by domsom
    I have a download worker that uses ThreadPool-threads to download files. After enhancing these to apply some Selenium tests to the downloaded files, I am constantly experiencing TimeOut-exceptions with the file downloaders and delays running the Selenium tests. More precisely: When the program starts, the download threads start downloading and a couple of pages are seamlessly processed via Selenium Shortly after, the first download threads start throwing TimeOut exceptions from HttpWebRequest. At the same time, commands stop flowing to Selenium (as observed in the SeleniumRC log), but the thread running Selenium is not getting any exception This situation holds as long as there are entries in the download list: new download threads are being started and terminate after receiving TimeOuts (without trying to lock Selenium) As soon as no more download threads are being started, Selenium starts receiving commands again and the threads waiting for the lock are processed sequentially as designed Now here's the download code: HttpWebRequest request = null; WebResponse response = null; Stream stream = null; StreamReader sr = null; try { request = (HttpWebRequest) WebRequest.Create(uri); request.ServicePoint.ConnectionLimit = MAX_CONNECTIONS_PER_HOST; response = request.GetResponse(); stream = response.GetResponseStream(); // Read the stream... } finally { if (request != null) request.Abort(); if (response != null) response.Close(); if (stream != null) { stream.Close(); stream.Dispose(); } if (sr != null) { sr.Close(); sr.Dispose(); } } And this is how Selenium is used afterwards in the same thread: lock(SeleniumLock) { selenium.Open(url); // Run some Selenium commands, but no selenium.stop() } Where selenium is a static variable that is initialized in the static constructor of the class (via selenium.start()). I assume I am running into the CLR connection limit, so I added these lines during initalization: ThreadPool.GetMaxThreads (out maxWorkerThreads, out maxCompletionPortThreads); HttpUtility.MAX_CONNECTIONS_PER_HOST = maxWorkerThreads; System.Net.ServicePointManager.DefaultConnectionLimit = maxWorkerThreads + 1; The + 1 is for the connection to the SeleniumRC, due to my guess that the Selenium client code also uses HttpWebRequest. It seems like I'm still running into some kind of deadlock - although the threads waiting for the Selenium lock do not hold any resources. Any ideas on how to get this working?

    Read the article

  • Does HttpWebRequest automatically take care of certificate validation?

    - by Kevin Pang
    I'm using an HttpWebRequest object to access a web service via an HTTP POST. Part of the requirement is that I: Verify that the URL in the certificate matches the URL I'm posting to Verify that the certificate is valid and trusted Verify that the certificate has not expired Does HttpWebRequest automatically handle that for me? I'd assume that if any of these conditions came up, I'd get the standard "could not establish trust relationship for the SSL/TLS secure channel" exception.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >