Search Results

Search found 349 results on 14 pages for 'webrequest'.

Page 8/14 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • 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

  • WCF/REST Get image into picturebox?

    - by Garrith
    So I have wcf rest service which succesfuly runs from a console app, if I navigate to: http://localhost:8000/Service/picture/300/400 my image is displayed note the 300/400 sets the width and height of the image within the body of the html page. The code looks like this: namespace WcfServiceLibrary1 { [ServiceContract] public interface IReceiveData { [OperationContract] [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Xml, UriTemplate = "picture/{width}/{height}")] Stream GetImage(string width, string height); } public class RawDataService : IReceiveData { public Stream GetImage(string width, string height) { int w, h; if (!Int32.TryParse(width, out w)) { w = 640; } // Handle error if (!Int32.TryParse(height, out h)) { h = 400; } Bitmap bitmap = new Bitmap(w, h); for (int i = 0; i < bitmap.Width; i++) { for (int j = 0; j < bitmap.Height; j++) { bitmap.SetPixel(i, j, (Math.Abs(i - j) < 2) ? Color.Blue : Color.Yellow); } } MemoryStream ms = new MemoryStream(); bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); ms.Position = 0; WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg"; return ms; } } } What I want to do now is use a client application "my windows form app" and add that image into a picturebox. Im abit stuck as to how this can be achieved as I would like the width and height of the image from my wcf rest service to be set by the width and height of the picturebox. I have tryed this but on two of the lines have errors and im not even sure if it will work as the code for my wcf rest service seperates width and height with a "/" if you notice in the url. string uri = "http://localhost:8080/Service/picture"; private void button1_Click(object sender, EventArgs e) { StringBuilder sb = new StringBuilder(); sb.AppendLine("<picture>"); sb.AppendLine("<width>" + pictureBox1.Image.Width + "</width>"); // the url looks like this http://localhost:8080/Service/picture/300/400 when accessing the image so I am trying to set this here sb.AppendLine("<height>" + pictureBox1.Image.Height + "</height>"); sb.AppendLine("</picture>"); string picture = sb.ToString(); byte[] getimage = Encoding.UTF8.GetBytes(picture); // not sure this is right HttpWebRequest req = WebRequest.Create(uri); //cant convert webrequest to httpwebrequest req.Method = "GET"; req.ContentType = "image/jpg"; req.ContentLength = getimage.Length; MemoryStream reqStrm = req.GetRequestStream(); //cant convert IO stream to IO Memory stream reqStrm.Write(getimage, 0, getimage.Length); reqStrm.Close(); HttpWebResponse resp = req.GetResponse(); // cant convert web respone to httpwebresponse MessageBox.Show(resp.StatusDescription); pictureBox1.Image = Image.FromStream(reqStrm); reqStrm.Close(); resp.Close(); } So just wondering if some one could help me out with this futile attempt at adding a variable image size from my rest service to a picture box on button click. This is the host app aswell: namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string baseAddress = "http://" + Environment.MachineName + ":8000/Service"; ServiceHost host = new ServiceHost(typeof(RawDataService), new Uri(baseAddress)); host.AddServiceEndpoint(typeof(IReceiveData), new WebHttpBinding(), "").Behaviors.Add(new WebHttpBehavior()); host.Open(); Console.WriteLine("Host opened"); Console.ReadLine();

    Read the article

  • The request was aborted: Could not create SSL/TLS secure channel.

    - by Simon
    We are enabled to connect to an https server using WebRequest because of this error message : The request was aborted: Could not create SSL/TLS secure channel. We know that the server aint got a valid https certificate with the path used (and we're not even sure if its fully release yet... ) but to bypass this issue, we use the following code that we've taken somewhere here in another post. [...] { ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(AllwaysGoodCertificate); } private static bool AllwaysGoodCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) { return true; } There problem is that server just never valide the certificate and fail we the error ... Anyone have any idea of what should I do? Thank and sorry for my english ... I'm from Quebec and usualy talk french!

    Read the article

  • IOException reading from HttpWebResponse response stream over SSL

    - by Lawrence Johnston
    I get the following exception when attempting to read the response from my HttpWebRequest: System.IO.IOException: Received an unexpected EOF or 0 bytes from the transport stream. at System.Net.ConnectStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.IO.StreamReader.ReadBuffer() at System.IO.StreamReader.ReadToEnd() ... My code functions without issue when using http. I am talking to a third-party device; I do not have access to the server code. My code is as follows: private string MakeRequest() { // Disable SSL certificate verification per // http://www.thejoyofcode.com/WCF_Could_not_establish_trust_relationship_for_the_SSL_TLS_secure_channel_with_authority.aspx ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; }); Uri uri = new Uri("https://mydevice/mypath"); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.Method = WebRequestMethods.Http.Get; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { using (StreamReader sr = new StreamReader(responseStream.)) { return sr.ReadToEnd(); } } } } Does anybody have any thoughts about what might be causing it?

    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

  • C# How to check if an FTP Directory Exists

    - by Billy Logan
    Hello Everyone, Looking for the best way to check for a given directory via FTP. currently i have the following code: private bool FtpDirectoryExists(string directory, string username, string password) { try { var request = (FtpWebRequest)WebRequest.Create(directory); request.Credentials = new NetworkCredential(username, password); request.Method = WebRequestMethods.Ftp.GetDateTimestamp; FtpWebResponse response = (FtpWebResponse)request.GetResponse(); } catch (WebException ex) { FtpWebResponse response = (FtpWebResponse)ex.Response; if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable) return false; else return true; } return true; } This returns false whether the directory is there or not. Can someone point me in the right direction. Thanks in advance, Billy

    Read the article

  • WebClient vs. HttpWebRequest/HttpWebResponse

    - by Dan
    It seems to me that most of what can be accomplished with HttpWebRequest/Response can also be accomplished with the WebClient class. I read somewhere that WebClient is a high-level wrapper for WebRequest/Response. So far, I can't see anything that can be accomplished with HttpWebRequest/Response that can not be accomplished with WebClient, nor where HttpWebRequest/Response will give you more "fine-grained" control. When should I use WebClient and when HttpWebRequest/Response? (Obviously, HttpWebRequest/Response are HTTP specific.) If HttpWebRequest/Response are lower level then WebClient, what can I accomplish with HttpWebRequest/Response that I cannot accomplish with WebClient?

    Read the article

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

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

    Read the article

  • How to set HTTP Headers from client class inherited from SoapHttpClientProtocol

    - by Alfred
    I'm using a class MyClass inherited from SoapHttpClientProtocol (auto-generated in my project by creating a WebReference from a .wsdl file, representing a service). Before calling a "WebMethod" of this service, I need to custom the http header of my request. I tried overloading the GetWebRequest() method of SoapHttpClientProtocol that way : public partial class MyClass: System.Web.Services.Protocols.SoapHttpClientProtocol{ protected override WebRequest GetWebRequest(Uri uri) { HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(uri); request.Headers.Add("MyCustomHeader", "MyCustomHeaderValue"); return request; } } I was hoping that GetWebRequest was called in the constructor of MyClass, apparently it's not. Could someone help me ?

    Read the article

  • C# File Exception: cannot access the file because it is being used by another process

    - by Lirik
    I'm trying to download a file from the web and save it locally, but I get an exception: C# The process cannot access the file 'blah' because it is being used by another process. This is my code: File.Create("data.csv"); // create the file request = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url)); request.Timeout = 30000; response = (HttpWebResponse)request.GetResponse(); using (Stream file = File.OpenWrite("data.csv"), // <-- Exception here input = response.GetResponseStream()) { // Save the file using Jon Skeet's CopyStream method CopyStream(input, file); } I've seen numerous other questions with the same exception, but none of them seem to apply here. Any help?

    Read the article

  • Very Slow WebResponse triggering TimeOut

    - by David Fdez
    Hello: I have a function in C# that fetches the status of Internet by retrieving a 64b XML from the router page public bool isOn() { HttpWebRequest hwebRequest = (HttpWebRequest)WebRequest.Create("http://" + this.routerIp + "/top_conn.xml"); hwebRequest.Timeout = 500; HttpWebResponse hWebResponse = (HttpWebResponse)hwebRequest.GetResponse(); XmlTextReader oXmlReader = new XmlTextReader(hWebResponse.GetResponseStream()); string value; while (oXmlReader.Read()) { value = oXmlReader.Value; if (value.Trim() != ""){ return !value.Substring(value.IndexOf("=") + 1, 1).Equals("0"); } } return false; } using Mozilla Firefox 3.5 & FireBug addon i guessed it normally takes 30ms to retrieve the page however at the very huge 500ms limit it stills reach it often. How can I dramatically improve the performance? Thanks in advance

    Read the article

  • C# Stream Reader adding \n to XML

    - by Terry
    I use the StreamReader class to obtain XML for my GeoCoding process from Google. StreamReader srGeoCode = new StreamReader(WebRequest.Create(Url).GetResponse().GetResponseStream()); String GeoCodeXml = srGeoCode.ReadToEnd(); XmlDocument XmlDoc = new XmlDocument(); GeoCode oGeoCode = new GeoCode(); XmlDoc.Load(GeoCodeXml); I get XML back but it adds \n and other extras to the XML <?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<kml xmlns=\"http://earth.google.com/kml/2.0\"><Response>\n <name> I have the same code in VB and it does not do this. I can successfully GeoCode my information using the VB version of this console app. Is there a reason the C# version adds this extra data to the XML that I retrieve back? I am trying my best to convert everything over to C#. I enjoy coding in it over VB.

    Read the article

  • Asp.net HttpWebResponse - how can I not depend on WebException for flow control?

    - by Campos
    I need to check whether the request will return a 500 Server Internal Error or not (so getting the error is expected). I'm doing this: HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "GET"; HttpWebResponse response = request.GetResponse() as HttpWebResponse; if (response.StatusCode == HttpStatusCode.OK) return true; else return false; But when I get the 500 Internal Server Error, a WebException is thrown, and I don't want to depend on it to control the application flow - how can this be done?

    Read the article

  • Passing Custom headers from .Net 1.1 client to a WCF service

    - by sreejith
    I have a simple wcf service which uses basicHttp binding, I want to pass few information from client to this service via custom SOAP header. My client is a .net application targetting .Net 1.1, using visual studio I have created the proxy( Added a new web reference pointing to my WCF service) I am able to call methods in the WCF service but not able to pass the data in message header. Tried to override "GetWebRequest" and added custom headers in the proxy but for some reason when I tried to access the header using "OperationContext.Current.IncomingMessageHeaders.FindHeader" it is not thier. Any idea how to solve this prob? This is how I added the headers protected override System.Net.WebRequest GetWebRequest(Uri uri) { HttpWebRequest request; request = (HttpWebRequest)base.GetWebRequest(uri); request.Headers.Add("tesData", "test"); return request; }

    Read the article

  • HELP! WebClient.UploadFile() throws exception while uploading files to sharepoint

    - by Royson
    In my application i am uploading files to sharepoint 2007. I am using using (WebClient webClient = new WebClient()) { webClient.Credentials = new NetworkCredential(userName, password); webClient.Headers.Add("Content-Type", "application/x-vermeer-urlencoded"); webClient.Headers.Add("X-Vermeer-Content-Type", "application/x-vermeer-urlencoded"); String result = Encoding.UTF8.GetString(webClient.UploadData(webUrl + "/_vti_bin/_vti_aut/author.dll","POST", data.ToArray())); } the code is running successfully..but for some files it throws exception The underlying connection was closed: The connection was closed unexpectedly. at System.Net.WebClient.UploadDataInternal(Uri address, String method, Byte[] data, WebRequest& request) at System.Net.WebClient.UploadData(Uri address, String method, Byte[] data) at System.Net.WebClient.UploadData(String address, String method, Byte[] data) Any Ideas what I have done wrong? I am using VS-2008 2.0

    Read the article

  • Getting error while transfering PGP file through FTP : The underlying connection was closed: An unex

    - by sumeet Sharma
    I am trying to upload a PGP encrypted file through FTP. But I am getting an error message as follows: The underlying connection was closed: An unexpected error occurred on a receive. I am using the following code and getting the error at line: Stream ftpStream = response.GetResponse(); Is there any one who can help me out ASAP. Following is the code sample: FtpWebRequest request = WebRequest.Create("ftp://ftp.website.com/sample.txt.pgp") as FtpWebRequest; request.UsePassive = true; FtpWebResponse response = request.GetResponse() as FtpWebResponse; Stream ftpStream = response.GetResponse(); int bufferSize = 8192; byte[] buffer = new byte[bufferSize]; using (FileStream fileStream = new FileStream("localfile.zip", FileMode.Create, FileAccess.Write)) { int nBytes; while((nBytes = ftpStream.Read(buffer, 0, bufferSize) > 0) { fileStream.Write(buffer, 0, nBytes); } } Regards, Sumeet

    Read the article

  • WebClient.UploadFile() throws exception while uploading files to sharepoint

    - by Royson
    In my application i am uploading files to sharepoint 2007. I am using using (WebClient webClient = new WebClient()) { webClient.Credentials = new NetworkCredential(userName, password); webClient.Headers.Add("Content-Type", "application/x-vermeer-urlencoded"); webClient.Headers.Add("X-Vermeer-Content-Type", "application/x-vermeer-urlencoded"); String result = Encoding.UTF8.GetString(webClient.UploadData(webUrl + "/_vti_bin/_vti_aut/author.dll","POST", data.ToArray())); } the code is running successfully..but for some files it throws exception The underlying connection was closed: The connection was closed unexpectedly. at System.Net.WebClient.UploadDataInternal(Uri address, String method, Byte[] data, WebRequest& request) at System.Net.WebClient.UploadData(Uri address, String method, Byte[] data) at System.Net.WebClient.UploadData(String address, String method, Byte[] data) Any Ideas what I have done wrong? I am using VS-2008 2.0

    Read the article

  • How to add correct cancellation when downloading a file with the example in the samples of the new P

    - by Mike
    Hello everybody, I have downloaded the last samples of the Parallel Programming team, and I don't succeed in adding correctly the possibility to cancel the download of a file. Here is the code I ended to have: var wreq = (HttpWebRequest)WebRequest.Create(uri); // Fire start event DownloadStarted(this, new DownloadStartedEventArgs(remoteFilePath)); long totalBytes = 0; wreq.DownloadDataInFileAsync(tmpLocalFile, cancellationTokenSource.Token, allowResume, totalBytesAction => { totalBytes = totalBytesAction; }, readBytes => { Log.Debug("Progression : {0} / {1} => {2}%", readBytes, totalBytes, 100 * (double)readBytes / totalBytes); DownloadProgress(this, new DownloadProgressEventArgs(remoteFilePath, readBytes, totalBytes, (int)(100 * readBytes / totalBytes))); }) .ContinueWith( (antecedent ) => { if (antecedent.IsFaulted) Log.Debug(antecedent.Exception.Message); //Fire end event SetEndDownload(antecedent.IsCanceled, antecedent.Exception, tmpLocalFile, 0); }, cancellationTokenSource.Token); I want to fire an end event after the download is finished, hence the ContinueWith. I slightly changed the code of the samples to add the CancellationToken and the 2 delegates to get the size of the file to download, and the progression of the download: return webRequest.GetResponseAsync() .ContinueWith(response => { if (totalBytesAction != null) totalBytesAction(response.Result.ContentLength); response.Result.GetResponseStream().WriteAllBytesAsync(filePath, ct, resumeDownload, progressAction).Wait(ct); }, ct); I had to add the call to the Wait function, because if I don't, the method exits and the end event is fired too early. Here are the modified method extensions (lot of code, apologies :p) public static Task WriteAllBytesAsync(this Stream stream, string filePath, CancellationToken ct, bool resumeDownload = false, Action<long> progressAction = null) { if (stream == null) throw new ArgumentNullException("stream"); // Copy from the source stream to the memory stream and return the copied data return stream.CopyStreamToFileAsync(filePath, ct, resumeDownload, progressAction); } public static Task CopyStreamToFileAsync(this Stream source, string destinationPath, CancellationToken ct, bool resumeDownload = false, Action<long> progressAction = null) { if (source == null) throw new ArgumentNullException("source"); if (destinationPath == null) throw new ArgumentNullException("destinationPath"); // Open the output file for writing var destinationStream = FileAsync.OpenWrite(destinationPath); // Copy the source to the destination stream, then close the output file. return CopyStreamToStreamAsync(source, destinationStream, ct, progressAction).ContinueWith(t => { var e = t.Exception; destinationStream.Close(); if (e != null) throw e; }, ct, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Current); } public static Task CopyStreamToStreamAsync(this Stream source, Stream destination, CancellationToken ct, Action<long> progressAction = null) { if (source == null) throw new ArgumentNullException("source"); if (destination == null) throw new ArgumentNullException("destination"); return Task.Factory.Iterate(CopyStreamIterator(source, destination, ct, progressAction)); } private static IEnumerable<Task> CopyStreamIterator(Stream input, Stream output, CancellationToken ct, Action<long> progressAction = null) { // Create two buffers. One will be used for the current read operation and one for the current // write operation. We'll continually swap back and forth between them. byte[][] buffers = new byte[2][] { new byte[BUFFER_SIZE], new byte[BUFFER_SIZE] }; int filledBufferNum = 0; Task writeTask = null; int readBytes = 0; // Until there's no more data to be read or cancellation while (true) { ct.ThrowIfCancellationRequested(); // Read from the input asynchronously var readTask = input.ReadAsync(buffers[filledBufferNum], 0, buffers[filledBufferNum].Length); // If we have no pending write operations, just yield until the read operation has // completed. If we have both a pending read and a pending write, yield until both the read // and the write have completed. yield return writeTask == null ? readTask : Task.Factory.ContinueWhenAll(new[] { readTask, writeTask }, tasks => tasks.PropagateExceptions()); // If no data was read, nothing more to do. if (readTask.Result <= 0) break; readBytes += readTask.Result; if (progressAction != null) progressAction(readBytes); // Otherwise, write the written data out to the file writeTask = output.WriteAsync(buffers[filledBufferNum], 0, readTask.Result); // Swap buffers filledBufferNum ^= 1; } } So basically, at the end of the chain of called methods, I let the CancellationToken throw an OperationCanceledException if a Cancel has been requested. What I hoped was to get IsFaulted == true in the appealing code and to fire the end event with the canceled flags and the correct exception. But what I get is an unhandled exception on the line response.Result.GetResponseStream().WriteAllBytesAsync(filePath, ct, resumeDownload, progressAction).Wait(ct); telling me that I don't catch an AggregateException. I've tried various things, but I don't succeed to make the whole thing work properly. Does anyone of you have played enough with that library and may help me? Thanks in advance Mike

    Read the article

  • Serializing an object into the body of a WCF request using webHttpBinding

    - by Bert
    I have a WCF service exposed with a webHttpBinding endpoint. [OperationContract(IsOneWay = true)] [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/?action=DoSomething&v1={value1}&v2={value2}")] void DoSomething(string value1, string value2, MySimpleObject value3); In theory, if I call this, the first two parameters (value1 & value 2) are taken from the Uri and the final one (value3) should be deserialized from the body of the request. Assuming I am using Json as the RequestFormat, what is the best way of serialising an instance of MySimpleObject into the body of the request before I send it ? This, for instance, does not seem to work : HttpWebRequest sendRequest = (HttpWebRequest)WebRequest.Create(url); sendRequest.ContentType = "application/json"; sendRequest.Method = "POST"; using (var sendRequestStream = sendRequest.GetRequestStream()) { DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(MySimpleObject)); jsonSerializer.WriteObject(sendRequestStream, obj); sendRequestStream.Close(); } sendRequest.GetResponse().Close();

    Read the article

  • How to receive userinfo with google adwords api libraries

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

    Read the article

  • Program skips code after trying to parse XML in VB.NET

    - by Bead
    I'm trying to parse some XML (html) I downloaded using WebRequest.Create() and then read it. However after loading the XML file using LoadXml(string), anything else I execute doesn't work. Setting a breakpoint on anything afterwards doesn't work and it doesn't break. I tried catching exception but none are occurring, so I'm not sure what the problem is. Here is my code: Dim reader As StreamReader = New StreamReader(HTTPResponse.GetResponseStream()) Dim xDoc As XmlDocument = New XmlDocument() xDoc.LoadXml(reader.ReadToEnd()) Dim omfg As String = xDoc.ChildNodes().Item(0).InnerText() Dim name As XmlNodeList = xDoc.GetElementsByTagName("div") Dim jj As Integer = name.Count For i As Integer = 0 To name.Count - 1 MessageBox.Show(name.Item(i).InnerText) Next i Anything after the "xDoc.LoadXml(reader.ReadToEnd())" doesn't execute.. Any ideas on this? My XML does have some whitespace at the beginning, I don't know if that is causing the problem...

    Read the article

  • Downloading a file in ASP.NET (through the server) while streaming it to the user

    - by James Teare
    My ASP.NET website currently downloads a file from a remote server to a local drive, although when users access the site they have to wait for the server to finish downloading the file until they can then download the file from my ASP.NET website. Is it possible to almost stream the download from the remote website - through my ASP.NET website directly to the user (a bit like a proxy) ? My current code is as follows: using (var client = new WebClientEx()) { client.DownloadFile(downloadURL, "outputfile.zip"); } WebClient class: public class WebClientEx : WebClient { public CookieContainer CookieContainer { get; private set; } public WebClientEx() { CookieContainer = new CookieContainer(); } protected override WebRequest GetWebRequest(Uri address) { var request = base.GetWebRequest(address); if (request is HttpWebRequest) { (request as HttpWebRequest).CookieContainer = CookieContainer; } return request; } }

    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

  • Illegal characters in path exception[closed]

    - by Neir0
    Hi I trying to get page from this url: YandexMarket but WebClient and httpWebRequest throw exception Illegal characters in path. HttpUtility.UrlEncode doesnt work for this symbol "-". Firefox and other browser are correctly open the page. Here is my code: public string GetPage(string url) { var wReq = (HttpWebRequest)WebRequest.Create(url); return new StreamReader(wReq.GetResponse().GetResponseStream()).ReadToEnd(); } How i can get the page? Sorry guys. All ok.

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14  | Next Page >