Search Results

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

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

  • HttpWebRequest issues

    - by Allen Ho
    Hi, Im still having issues using HttpWebRequest. For some reason sometimes in my app the call just times out... HttpWebRequest req = null; req = (HttpWebRequest)WebRequest.CreateDefault(new Uri(aRequest)); req.PreAuthenticate = true; req.AllowAutoRedirect = true; req.KeepAlive = false; ..... resp = (HttpWebResponse)req.GetResponse(); resp.close(); I am closing the response but Im just wondering if it is more likely to fail since Im making requests all over the place? I tried playing around with the ServicePointManager class hoping it would help but it hasnt really System.Net.ServicePointManager.DefaultConnectionLimit = 100; System.Net.ServicePointManager.MaxServicePoints = 100;

    Read the article

  • Opening response stream in silverlight

    - by John Maloney
    Hello, I am attempting to return a image from a server using Silverlight 3. The server returns the Response stream like this: context.Response.ContentType = imageFactory.ContentType imgStream.WriteTo(context.Response.OutputStream) imgStream.Close() context.Response.End() On the Silverlight client I am handling the stream like: Dim request As HttpWebRequest = result.AsyncState Dim response As HttpWebResponse = request.EndGetResponse(result) Dim responseStream As IO.Stream = response.GetResponseStream() I want to take that stream and open the browsers save dialog, one option I have explored is using the Html.Window.Navigate(New Uri("image url")) and this opened the correct browser default dialog but it is not an option because I need to send extended information(e.g. XML) to the server through the HttpRequest.Headers.Item and the Navigate doesn't allow this. How can I take a Response Stream and force the default browser Save dialog to appear from the Silverlight Application without using the Html.Window.Navigate(New Uri("image url"))?

    Read the article

  • post data through httpWebRequest

    - by user304901
    Hello, everybody. I need to "Post" some data to an external website using HttpWebRequest object from my application(desktop) and get a response back into my application through HttpWebResponse object. But the webpage on which i m posting data have textboxes which have dynamic names. how can i get the name of those textboxes and post data in httpwebresquest. for example when i load the page the textbox name is like this "U2FsdGVkX183MTQyNzE0MrhLOmUpqd3eL60xF19RmCwLlSiG5nC1H6wvtBDhjI3uM1krX_B8Fwc" but when i refresh the page name change to this "U2FsdGVkX182MjMwNjIzMPAtotst_q9PP9TETomXB453Mq3M3ZY5HQt70ZeyxbRb118Y8GQbgP8" Thanks for any suggestions.

    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

  • Most efficient way for testing links

    - by Burnzy
    I'm currently developping an app that is going through all the files on a server and checking every single hrefs to check wether they are valid or not. Using a WebClient or a HttpWebRequest/HttpWebResponse is kinda overkilling the process because it downloads the whole page each time, which is useless, I only need to check if the link do not return 404. What would be the most efficient way? Socket seems to be a good way of doing it, however I'm not quite sure how this works. Thanks for sharing your expertise!

    Read the article

  • How do I prevent an https response from throwing an AuthenticationException with Fiddler running?

    - by Ichabod Clay
    Relative newbie to C# here :) I'm currently creating a web link scraper and having issues with the responses I'm getting when trying to login to the website via my program. I'm trying to use Fiddler to see if my program is sending the proper data, but my program is throwing an AuthenticationException when trying to get a response from the site with Fiddler running. The requests are being sent over HTTPS and Fiddler's certificate is the cause of the excepting being thrown. My question is, what can I implement into my program to have it disregard the certificate authentication? As far as my program goes, the requests and responses are being handled by HttpWebRequest and HttpWebResponse classes.

    Read the article

  • Scenarios for Throwing Exceptions

    - by Joe Mayo
    I recently came across a situation where someone had an opinion that differed from mine of when an exception should be thrown. This particular case was an issue opened on LINQ to Twitter for an Exception on EndSession.  The premise of the issue was that the poster didn’t feel an exception should be raised, regardless of authentication status.  As first, this sounded like a valid point.  However, I went back to review my code and decided not to make any changes. Here's my rationale: 1. The exception doesn’t occur if the user is authenticated when EndAccountSession is called. 2. The exception does occur if the user is not authenticated when EndAccountSession is called. 3. The exception represents the fact that EndAccountSession is not able to fulfill its intended purpose - to end the session.  If a session never existed, then it would not be possible to perform the requested action.  Therefore, an exception is appropriate. To help illustrate how to handle this situation, I've modified the following code in Program.cs in the LinqToTwitterDemo project to illustrate the situation: static void EndSession(ITwitterAuthorizer auth) { using (var twitterCtx = new TwitterContext(auth, "https://api.twitter.com/1/", "https://search.twitter.com/")) { try { //Log twitterCtx.Log = Console.Out; var status = twitterCtx.EndAccountSession(); Console.WriteLine("Request: {0}, Error: {1}" , status.Request , status.Error); } catch (TwitterQueryException tqe) { var webEx = tqe.InnerException as WebException; if (webEx != null) { var webResp = webEx.Response as HttpWebResponse; if (webResp != null && webResp.StatusCode == HttpStatusCode.Unauthorized) Console.WriteLine("Twitter didn't recognize you as having been logged in. Therefore, your request to end session is illogical.\n"); } var status = tqe.Response; Console.WriteLine("Request: {0}, Error: {1}" , status.Request , status.Error); } } } As expected, LINQ to Twitter wraps the exception in a TwitterQueryException as the InnerException.  The TwitterQueryException serves a very useful purpose through it's Response property.  Notice in the example above that the response has Request and Error proprieties.  These properties correspond to the information that Twitter returns as part of it's response payload.  This is often useful while debugging to help you understand why Twitter was unable to perform the  requested action.  Other times, it's cryptic, but that's another story.  At least you have some way of knowing in your code how to anticipate and handle these situations, along with having extra information to debug with. To sum things up, there are two points to make: when and why an exception should be raised and when to wrap and re-throw an exception in a custom exception type. I felt it was necessary to allow the exception to be raised because the called method was unable to perform the task it was designed for.  I also felt that it is inappropriate for a general library to do anything with exceptions because that could potentially hide a problem from the caller.  A related point is that it should be the exclusive decision of the application that uses the library on what to do with an exception.  Another aspect of this situation is that I wrapped the exception in a custom exception and re-threw.  This is a tough call because I don’t want to hide any stack trace information.  However, the need to make the exception more meaningful by including vital information returned from Twitter swayed me in the direction to design an interface that was as helpful as possible to library consumers.  As shown in the code above, you can dig into the exception and pull out a lot of good information, such as the fact that the underlying HTTP response was a 401 Unauthorized.  In all, trade-offs are seldom perfect for all cases, but combining the fact that the method was unable to perform its intended function, this is a library, and the extra information can be more helpful, it seemed to be the better design. @JoeMayo

    Read the article

  • Downloading attachments from Exchange with WebDAV

    - by arturito
    Hi there! I've been trying to retrive attachment from message in Exchange server using WebDAV.I don't know which version of Exchange the company is running. I'can successfully read messages and retrive list of attachments. However I am failing to save attachments. In both cases errors is: "The remote server returned an error: <403 Forbidden. Any idea what I'm doing wrong? My code: static void Main(string[] args) { HttpWebRequest Request; WebResponse Response; CredentialCache MyCredentialCache; string attachment = "http://mailserver/Exchange/Username/Inbox/Test.EML/Test.txt"; string strUserName = "username"; string strPassword = "password"; string strDomain = "domain"; try { // HttpWebRequest MyCredentialCache = new System.Net.CredentialCache(); MyCredentialCache.Add(new System.Uri(attachment), "NTLM", new NetworkCredential(strUserName, strPassword, strDomain)); Request = (HttpWebRequest)HttpWebRequest.Create(attachment); Request.Credentials = MyCredentialCache; Request.Method = "GET"; Response = (HttpWebResponse)Request.GetResponse(); } catch(Exception ex) { Console.WriteLine(ex.Message.ToString()); } try { //Web Client string downloadPath = "D:\\Downloads"; WebClient wcClient = new WebClient(); wcClient.Credentials = new NetworkCredential(strUserName, strPassword, strDomain); string file = Path.GetFileName(attachment); string filename = Path.Combine(downloadPath, file); wcClient.DownloadFile(attachment, filename); } catch (Exception ex) { Console.WriteLine(ex.Message.ToString()); } Console.ReadLine(); }

    Read the article

  • How to log in to a vbulletin forum with C#?

    - by Yustme
    Hi, I'm trying to log into a vbulletin forum. I got this far: private string login(string url, string username, string password) { string values = "vb_login_username={0}&vb_login_password={1}" values += "&securitytoken=guest&cookieuser=checked&do=login"; values = string.Format(values, username, password); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); CookieContainer a = new CookieContainer(); req.CookieContainer = a; System.Net.ServicePointManager.Expect100Continue = false; // prevents 417 error using (StreamWriter writer = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII)) { writer.Write(values); } this.response = (HttpWebResponse)req.GetResponse(); StringBuilder output = new StringBuilder(); foreach (var cookie in response.Cookies) { output.Append(cookie.ToString()); output.Append(";"); } return output.ToString(); } It looks like i am getting logged in, but when i download the page, i can't find my username in it. Do you guys see anything that i might be doing wrong? Thanks in advance!

    Read the article

  • This property cannot be set after writing has started! on a C# WebRequest Object

    - by EBAGHAKI
    I want to reuse a WebRequest object so that cookies and session would be saved for later request to the server. Below is my code. If i use Post function twice on the second time at request.ContentLength = byteArray.Length; it will throw an exception This property cannot be set after writing has started! But as you can see dataStream.Close(); Should close the writing process! Anybody knows what's going on? static WebRequest request; public MainForm() { request = WebRequest.Create("http://localhost/admin/admin.php"); } static string Post(string url, string data) { request.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(data); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = byteArray.Length; Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); WebResponse response = request.GetResponse(); Console.WriteLine(((HttpWebResponse)response).StatusDescription); dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); Console.WriteLine(responseFromServer); reader.Close(); dataStream.Close(); response.Close(); request.Abort(); return responseFromServer; }

    Read the article

  • Mysterious socket / HttpWebRequest timeouts

    - by Daniel Mošmondor
    I have a great app for capturing shoutcast streams :-) . So far, it worked with a charm on dozens of machines, and never exhibited behaviour I found now, which is ultimately very strange. I use HttpWebRequest to connect to the shoutcast server and when I connect two streams, everything's OK. When I go for third one, response = (HttpWebResponse)request.GetResponse(); throws with Connection Timeout exception. WTF? I must point out that I had to create .config for the application in order to allow my headers to be sent out from the application, otherwise it wouldn't work at all. Here it is: <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.net> <settings> <httpWebRequest useUnsafeHeaderParsing = "true" /> </settings> </system.net> </configuration> Does any of this ring a bell?

    Read the article

  • WCF, IIS6.0 (413) Request Entity Too Large.

    - by Andrew Kalashnikov
    Hello, guys. I've got annoyed problem. I've got WCF service(basicHttpBinding with Transport security Https). This service implements contract which consists 2 methods. LoadData. GetData. GetData works OK!. My client received pachage ~2Mb size without problems. All work correctly. But when I try load data by bool LoadData(Stream data); - signature of method I'll get (413) Request Entity Too Large. Stack Trace: Server stack trace: ? ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory factory, WebException responseException, ChannelBinding channelBinding) System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout) System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout) System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout) I try this http://blogs.msdn.com/jiruss/archive/2007/04/13/http-413-request-entity-too-large-can-t-upload-large-files-using-iis6.aspx. But it doesn't work! My server is 2003 with IIS6.0. Please help.

    Read the article

  • POST variables to web server?

    - by OverTheRainbow
    Hello I've been trying several things from Google to POST data to a web server, but none of them work: I'm still stuck at how to convert the variables into the request, considering that the second variable is an SQL query so it has spaces. Does someone know the correct way to use a WebClient to POST data? I'd rather use WebClient because it requires less code than HttpWebRequest/HttpWebResponse. Here's what I tried so far: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim wc = New WebClient() 'convert data wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded") Dim postData = String.Format("db={0}&query={1}", _ HttpUtility.UrlEncode("books.sqlite"), _ HttpUtility.UrlEncode("SELECT id,title FROM boooks")) 'Dim bytArguments As Byte() = Encoding.ASCII.GetBytes("db=books.sqlite|query=SELECT * FROM books") 'POST query Dim bytRetData As Byte() = wc.UploadData("http://localhost:9999/get", "POST", postData) RichTextBox1.Text = Encoding.ASCII.GetString(bytRetData) Exit Sub Dim client = New WebClient() Dim nv As New Collection nv.Add("db", "books.sqlite") nv.Add("query", "SELECT id,title FROM books") Dim address As New Uri("http://localhost:9999/get") 'Dim bytRetData As Byte() = client.UploadValues(address, "POST", nv) RichTextBox1.Text = Encoding.ASCII.GetString(bytRetData) Exit Sub 'Dim wc As New WebClient() 'convert data wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded") Dim bytArguments As Byte() = Encoding.ASCII.GetBytes("db=books.sqlite|query=SELECT * FROM books") 'POST query 'Dim bytRetData As Byte() = wc.UploadData("http://localhost:9999/get", "POST", bytArguments) RichTextBox1.Text = Encoding.ASCII.GetString(bytRetData) Exit Sub End Sub Thank you.

    Read the article

  • Getting 404 page not found connecting to webDAV

    - by Cragly
    I am trying to connect to a secure webDAV folder and download a file. I am having problems just trying to get a response from the server and as it keeps giving me a 404 page not found error as soon as I call Request.GetResponse(). I can connect to the webDAV folder using Windows Explorer by mapping a drive but cannot seem to do this in code. I have looked at other post on this site and others online but most seem to concentrate on connecting to Outlook. Has anybody else had this issue? The code I am using is as follows: string URI = "https://transfer.mycompany.com/myDirectory/myFile.csv"; string username = "username"; string password = "password"; Request = (HttpWebRequest) WebRequest.Create(URI); Request.Credentials = new NetworkCredential(username, password); Request.Method = WebRequestMethods.Http.Get; Request.Headers.Add("Translate", "f"); Response = (HttpWebResponse) Request.GetResponse(); contentLength = Convert.ToInt64(Response.GetResponseHeader("Content-Length"));

    Read the article

  • WCF REST adding data using POST or PUT 400 Bad Request

    - by user55474
    HI How do i add data using wcf rest architecture. I dont want to use the channelfactory to call my method. Something similar to the webrequest and webresponse used for GET. Something similar to the ajax WebServiceProxy restInvoke Or do i always have to use the Webchannelfactory implementation I am getting a 400 BAD request by using the following Dim url As String = "http://localhost:4475/Service.svc/Entity/Add" Dim req As WebRequest = WebRequest.Create(url) req.Method = "POST" req.ContentType = "application/xml; charset=utf-8" req.Timeout = 30000 req.Headers.Add("SOAPAction", url) Dim xEle As XElement xEle = <Entity xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <Name>Entity1</Name> </Entity> Dim sXML As String = xEle .Value req.ContentLength = sXML.Length Dim sw As New System.IO.StreamWriter(req.GetRequestStream()) sw.Write(sXML) sw.Close() Dim res as HttpWebResponse = req.GetResponse() Sercice Contract is as follows <OperationContract()> _ <WebInvoke(Method:="PUT", UriTemplate:="Entity/Add")> _ Function AddEntity(ByVal e1 As Entity) DataContract is as follows <Serializable()> _ <DataContract()> _ Public Class Entity private m_Name as String <DataMember()> _ Public Property Name() As String Get Return m_Name End Get Set(ByVal value As String) m_Name = value End Set End Property End Class thanks

    Read the article

  • Getting 404 Not Found connecting to webDAV

    - by Cragly
    I am trying to connect to a secure webDAV folder and download a file. I am having problems just trying to get a response from the server and as it keeps giving me a 404 Not Found error as soon as I call Request.GetResponse(). I can connect to the webDAV folder using Windows Explorer by mapping a drive but cannot seem to do this in code. I have looked at other post on this site and others online but most seem to concentrate on connecting to Outlook. Has anybody else had this issue? The code I am using is as follows: string URI = "https://transfer.mycompany.com/myDirectory/myFile.csv"; string username = "username"; string password = "password"; Request = (HttpWebRequest) WebRequest.Create(URI); Request.Credentials = new NetworkCredential(username, password); Request.Method = WebRequestMethods.Http.Get; Request.Headers.Add("Translate", "f"); Response = (HttpWebResponse) Request.GetResponse(); contentLength = Convert.ToInt64(Response.GetResponseHeader("Content-Length"));

    Read the article

  • P0ST variables to web server?

    - by OverTheRainbow
    Hello I've been trying several things from Google to POST data to a web server, but none of them work: I'm still stuck at how to convert the variables into the request, considering that the second variable is an SQL query so it has spaces. Does someone know the correct way to use a WebClient to POST data? I'd rather use WebClient because it requires less code than HttpWebRequest/HttpWebResponse. Here's what I tried so far: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim wc = New WebClient() 'convert data wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded") Dim postData = String.Format("db={0}&query={1}", _ HttpUtility.UrlEncode("books.sqlite"), _ HttpUtility.UrlEncode("SELECT id,title FROM boooks")) 'Dim bytArguments As Byte() = Encoding.ASCII.GetBytes("db=books.sqlite|query=SELECT * FROM books") 'POST query Dim bytRetData As Byte() = wc.UploadData("http://localhost:9999/get", "POST", postData) RichTextBox1.Text = Encoding.ASCII.GetString(bytRetData) Exit Sub Dim client = New WebClient() Dim nv As New Collection nv.Add("db", "books.sqlite") nv.Add("query", "SELECT id,title FROM books") Dim address As New Uri("http://localhost:9999/get") 'Dim bytRetData As Byte() = client.UploadValues(address, "POST", nv) RichTextBox1.Text = Encoding.ASCII.GetString(bytRetData) Exit Sub 'Dim wc As New WebClient() 'convert data wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded") Dim bytArguments As Byte() = Encoding.ASCII.GetBytes("db=books.sqlite|query=SELECT * FROM books") 'POST query 'Dim bytRetData As Byte() = wc.UploadData("http://localhost:9999/get", "POST", bytArguments) RichTextBox1.Text = Encoding.ASCII.GetString(bytRetData) Exit Sub End Sub Thank you.

    Read the article

  • Trying to use HttpWebRequest to load a page in a file.

    - by Malcolm
    Hi, I have a ASP.NET MVC app that works fine in the browser. I am using the following code to be able to write the html of a retrieved page to a file. (This is to use in a PDF conversion component) But this code errors out continually but not in the browser. I get timeout errors sometimes asn 500 errors. Public Function GetPage(ByVal url As String, ByVal filename As String) As Boolean Dim request As HttpWebRequest Dim username As String Dim password As String Dim docid As String Dim poststring As String Dim bytedata() As Byte Dim requestStream As Stream Try username = "pdfuser" password = "pdfuser" docid = "docid=inv12154" poststring = String.Format("username={0}&password={1}&{2}", username, password, docid) bytedata = Encoding.UTF8.GetBytes(poststring) request = WebRequest.Create(url) request.Method = "Post" request.ContentLength = bytedata.Length request.ContentType = "application/x-www-form-urlencoded" requestStream = request.GetRequestStream() requestStream.Write(bytedata, 0, bytedata.Length) requestStream.Close() request.Timeout = 60000 Dim response As HttpWebResponse Dim responseStream As Stream Dim reader As StreamReader Dim sb As New StringBuilder() Dim line As String = String.Empty response = request.GetResponse() responseStream = response.GetResponseStream() reader = New StreamReader(responseStream, System.Text.Encoding.ASCII) line = reader.ReadLine() While (Not line Is Nothing) sb.Append(line) line = reader.ReadLine() End While File.WriteAllText(filename, sb.ToString()) Catch ex As Exception MsgBox(ex.Message) End Try Return True End Function

    Read the article

  • Fails proceeding after POSTing to web server

    - by OverTheRainbow
    Hello According to this question, it seems like the error "Too many automatic redirections were attempted" is caused when forgetting to use a cookiecontainer to connect to a web server that uses cookies to keep track of the user. However, even though I used "request.CookieContainer = MyCookieContainer", I'm still getting into an endless loop that is terminated by VB Express with this error message. Imports System.IO Imports System.Net 'Remember to add reference to System.Web DLL Imports System.Web Imports System.Text Public Class Form1 Const ConnectURL = "http://www.acme.com/logon.php" Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim request As HttpWebRequest = WebRequest.Create(ConnectURL) 'Build POST data request.Method = "POST" request.ContentType = "application/x-www-form-urlencoded" Dim Data As New StringBuilder Data.Append("Account=" + HttpUtility.UrlEncode("jdoe")) Data.Append("&Password=" + HttpUtility.UrlEncode("test")) Dim byteData() As Byte byteData = UTF8Encoding.UTF8.GetBytes(Data.ToString()) request.ContentLength = byteData.Length Dim postStream As Stream = Nothing Try postStream = request.GetRequestStream() postStream.Write(byteData, 0, byteData.Length) Finally If Not postStream Is Nothing Then postStream.Close() End Try 'Dim MyCookieContainer As New CookieContainer Dim MyCookieContainer As CookieContainer = New CookieContainer() request.CookieContainer = MyCookieContainer 'Makes no difference 'request.KeepAlive = True 'request.AllowAutoRedirect = True Dim response As HttpWebResponse 'HERE '"Too many automatic redirections were attempted" response = request.GetResponse() Dim reader As StreamReader = New StreamReader(response.GetResponseStream()) RichTextBox1.Text = reader.ReadToEnd End Sub End Class This is probably a newbie issue, but I don't know what else to try. Any idea? Thank you for any hint.

    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

  • i not find how in powershell pass through http autentification then use a webservices (lotus/domino)

    - by user1716616
    We have here a domino/lotus webservices i want use with powershell. probleme is in front of webservices lotus admin ask a http autentification. how i can use this webservice?? here what i tryed first scrap the first page and get cookie. $url = "http://xxxxxxx/names.nsf?Login" $CookieContainer = New-Object System.Net.CookieContainer $postData = "Username=web.services&Password=jesuisunestar" $buffer = [text.encoding]::ascii.getbytes($postData) [net.httpWebRequest] $req = [net.webRequest]::create($url) $req.method = "POST" $req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" $req.Headers.Add("Accept-Language: en-US") $req.Headers.Add("Accept-Encoding: gzip,deflate") $req.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7") $req.AllowAutoRedirect = $false $req.ContentType = "application/x-www-form-urlencoded" $req.ContentLength = $buffer.length $req.TimeOut = 50000 $req.KeepAlive = $true $req.Headers.Add("Keep-Alive: 300"); $req.CookieContainer = $CookieContainer $reqst = $req.getRequestStream() $reqst.write($buffer, 0, $buffer.length) $reqst.flush() $reqst.close() [net.httpWebResponse] $res = $req.getResponse() $resst = $res.getResponseStream() $sr = new-object IO.StreamReader($resst) $result = $sr.ReadToEnd() this seem work but now no idea how i can use cookie with a webservicesproxy??? ps: i success have this to work with c# + visualstudio (just the class reference is autobuilt and i don't understand half of this but it allow me to use .CookieContenaire on the generated webservice )

    Read the article

  • Loading XML from Web Service

    - by Lukasz
    I am connecting to a web service to get some data back out as xml. The connection works fine and it returns the xml data from the service. var remoteURL = EveApiUrl; var postData = string.Format("userID={0}&apikey={1}&characterID={2}", UserId, ApiKey, CharacterId); var request = (HttpWebRequest)WebRequest.Create(remoteURL); request.Method = "POST"; request.ContentLength = postData.Length; request.ContentType = "application/x-www-form-urlencoded"; // Setup a stream to write the HTTP "POST" data var WebEncoding = new ASCIIEncoding(); var byte1 = WebEncoding.GetBytes(postData); var newStream = request.GetRequestStream(); newStream.Write(byte1, 0, byte1.Length); newStream.Close(); var response = (HttpWebResponse)request.GetResponse(); var receiveStream = response.GetResponseStream(); var readStream = new StreamReader(receiveStream, Encoding.UTF8); var webdata = readStream.ReadToEnd(); Console.WriteLine(webdata); This prints out the xml that comes from the service. I can also save the xml as an xml file like so; TextWriter writer = new StreamWriter(@"C:\Projects\TrainingSkills.xml"); writer.WriteLine(webdata); writer.Close(); Now I can load the file as an XDocument to perform queries on it like this; var data = XDocument.Load(@"C:\Projects\TrainingSkills.xml"); What my problem is that I don't want to save the file and then load it back again. When I try to load directly from the stream I get an exception, Illegal characters in path. I don't know what is going on, if I can load the same xml as a text file why can't I load it as a stream. The xml is like this; <?xml version='1.0' encoding='UTF-8'?> <eveapi version="2"> <currentTime>2010-04-28 17:58:27</currentTime> <result> <currentTQTime offset="1">2010-04-28 17:58:28</currentTQTime> <trainingEndTime>2010-04-29 02:48:59</trainingEndTime> <trainingStartTime>2010-04-28 00:56:42</trainingStartTime> <trainingTypeID>3386</trainingTypeID> <trainingStartSP>8000</trainingStartSP> <trainingDestinationSP>45255</trainingDestinationSP> <trainingToLevel>4</trainingToLevel> <skillInTraining>1</skillInTraining> </result> <cachedUntil>2010-04-28 18:58:27</cachedUntil> </eveapi> Thanks for your help!

    Read the article

  • HttpWebRequest possibly slowing website

    - by Steven Smith
    Using Visual studio 2012, C#.net 4.5 , SQL Server 2008, Feefo, Nopcommerce Hey guys I have Recently implemented a new review service into a current site we have. When the change went live the first day all worked fine. Since then though the sending of sales to Feefo hasnt been working, There are no logs either of anything going wrong. In the OrderProcessingService.cs in Nop Commerce's Service, i call a HttpWebrequest when an order has been confirmed as completed. Here is the code. var email = HttpUtility.UrlEncode(order.Customer.Email.ToString()); var name = HttpUtility.UrlEncode(order.Customer.GetFullName().ToString()); var description = HttpUtility.UrlEncode(productVariant.ProductVariant.Product.MetaDescription != null ? productVariant.ProductVariant.Product.MetaDescription.ToString() : "product"); var orderRef = HttpUtility.UrlEncode(order.Id.ToString()); var productLink = HttpUtility.UrlEncode(string.Format("myurl/p/{0}/{1}", productVariant.ProductVariant.ProductId, productVariant.ProductVariant.Name.Replace(" ", "-"))); string itemRef = ""; try { itemRef = HttpUtility.UrlEncode(productVariant.ProductVariant.ProductId.ToString()); } catch { itemRef = "0"; } var url = string.Format("feefo Url", login, password,email,name,description,orderRef,productLink,itemRef); var request = (HttpWebRequest)WebRequest.Create(url); request.KeepAlive = false; request.Timeout = 5000; request.Proxy = null; using (var response = (HttpWebResponse)request.GetResponse()) { if (response.StatusDescription == "OK") { var stream = response.GetResponseStream(); if(stream != null) { using (var reader = new StreamReader(stream)) { var content = reader.ReadToEnd(); } } } } So as you can see its a simple webrequest that is processed on an order, and all product variants are sent to feefo. Now: this hasnt been happening all week since the 15th (day of the implementation) the site has been grinding to a halt recently. The stream and reader in the the var content is there for debugging. Im wondering does the code redflag anything to you that could relate to the process of website? Also note i have run some SQL statements to see if there is any deadlocks or large escalations, so far seems fine, Logs have also been fine just the usual logging of Bots. Any help would be much appreciated! EDIT: also note that this code is in a method that is called and wrapped in A try catch UPDATE: well forget about the "not sending", thats because i was just told my code was rolled back last week

    Read the article

  • REST to Objects in C#

    RESTful interfaces for web services are all the rage for many Web 2.0 sites.  If you want to consume these in a very simple fashion, LINQ to XML can do the job pretty easily in C#.  If you go searching for help on this, youll find a lot of incomplete solutions and fairly large toolkits and frameworks (guess how I know this) this quick article is meant to be a no fluff just stuff approach to making this work. POCO Objects Lets assume you have a Model that you want to suck data into from a RESTful web service.  Ideally this is a Plain Old CLR Object, meaning it isnt infected with any persistence or serialization goop.  It might look something like this: public class Entry { public int Id; public int UserId; public DateTime Date; public float Hours; public string Notes; public bool Billable;   public override string ToString() { return String.Format("[{0}] User: {1} Date: {2} Hours: {3} Notes: {4} Billable {5}", Id, UserId, Date, Hours, Notes, Billable); } } Not that this isnt a completely trivial object.  Lets look at the API for the service.  RESTful HTTP Service In this case, its TickSpots API, with the following sample output: <?xml version="1.0" encoding="UTF-8"?> <entries type="array"> <entry> <id type="integer">24</id> <task_id type="integer">14</task_id> <user_id type="integer">3</user_id> <date type="date">2008-03-08</date> <hours type="float">1.00</hours> <notes>Had trouble with tribbles.</notes> <billable>true</billable> # Billable is an attribute inherited from the task <billed>true</billed> # Billed is an attribute to track whether the entry has been invoiced <created_at type="datetime">Tue, 07 Oct 2008 14:46:16 -0400</created_at> <updated_at type="datetime">Tue, 07 Oct 2008 14:46:16 -0400</updated_at> # The following attributes are derived and provided for informational purposes: <user_email>[email protected]</user_email> <task_name>Remove converter assembly</task_name> <sum_hours type="float">2.00</sum_hours> <budget type="float">10.00</budget> <project_name>Realign dilithium crystals</project_name> <client_name>Starfleet Command</client_name> </entry> </entries> Im assuming in this case that I dont necessarily care about all of the data fields the service is returning I just need some of them for my applications purposes.  Thus, you can see there are more elements in the <entry> XML than I have in my Entry class. Get The XML with C# The next step is to get the XML.  The following snippet does the heavy lifting once you pass it the appropriate URL: protected XElement GetResponse(string uri) { var request = WebRequest.Create(uri) as HttpWebRequest; request.UserAgent = ".NET Sample"; request.KeepAlive = false;   request.Timeout = 15 * 1000;   var response = request.GetResponse() as HttpWebResponse;   if (request.HaveResponse == true && response != null) { var reader = new StreamReader(response.GetResponseStream()); return XElement.Parse(reader.ReadToEnd()); } throw new Exception("Error fetching data."); } This is adapted from the Yahoo Developer article on Web Service REST calls.  Once you have the XML, the last step is to get the data back as your POCO. Use LINQ-To-XML to Deserialize POCOs from XML This is done via the following code: public IEnumerable<Entry> List(DateTime startDate, DateTime endDate) { string additionalParameters = String.Format("start_date={0}&end_date={1}", startDate.ToShortDateString(), endDate.ToShortDateString()); string uri = BuildUrl("entries", additionalParameters);   XElement elements = GetResponse(uri);   var entries = from e in elements.Elements() where e.Name.LocalName == "entry" select new Entry { Id = int.Parse(e.Element("id").Value), UserId = int.Parse(e.Element("user_id").Value), Date = DateTime.Parse(e.Element("date").Value), Hours = float.Parse(e.Element("hours").Value), Notes = e.Element("notes").Value, Billable = bool.Parse(e.Element("billable").Value) }; return entries; }   For completeness, heres the BuildUrl method for my TickSpot API wrapper: // Change these to your settings protected const string projectDomain = "DOMAIN.tickspot.com"; private const string authParams = "[email protected]&password=MyTickSpotPassword";   protected string BuildUrl(string apiMethod, string additionalParams) { if (projectDomain.Contains("DOMAIN")) { throw new ApplicationException("You must update your domain in ProjectRepository.cs."); } if (authParams.Contains("MyTickSpotPassword")) { throw new ApplicationException("You must update your email and password in ProjectRepository.cs."); } return string.Format("https://{0}/api/{1}?{2}&{3}", projectDomain, apiMethod, authParams, additionalParams); } Thats it!  Now go forth and consume XML and map it to classes you actually want to work with.  Have fun! Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • REST to Objects in C#

    RESTful interfaces for web services are all the rage for many Web 2.0 sites.  If you want to consume these in a very simple fashion, LINQ to XML can do the job pretty easily in C#.  If you go searching for help on this, youll find a lot of incomplete solutions and fairly large toolkits and frameworks (guess how I know this) this quick article is meant to be a no fluff just stuff approach to making this work. POCO Objects Lets assume you have a Model that you want to suck data into from a RESTful web service.  Ideally this is a Plain Old CLR Object, meaning it isnt infected with any persistence or serialization goop.  It might look something like this: public class Entry { public int Id; public int UserId; public DateTime Date; public float Hours; public string Notes; public bool Billable;   public override string ToString() { return String.Format("[{0}] User: {1} Date: {2} Hours: {3} Notes: {4} Billable {5}", Id, UserId, Date, Hours, Notes, Billable); } } Not that this isnt a completely trivial object.  Lets look at the API for the service.  RESTful HTTP Service In this case, its TickSpots API, with the following sample output: <?xml version="1.0" encoding="UTF-8"?> <entries type="array"> <entry> <id type="integer">24</id> <task_id type="integer">14</task_id> <user_id type="integer">3</user_id> <date type="date">2008-03-08</date> <hours type="float">1.00</hours> <notes>Had trouble with tribbles.</notes> <billable>true</billable> # Billable is an attribute inherited from the task <billed>true</billed> # Billed is an attribute to track whether the entry has been invoiced <created_at type="datetime">Tue, 07 Oct 2008 14:46:16 -0400</created_at> <updated_at type="datetime">Tue, 07 Oct 2008 14:46:16 -0400</updated_at> # The following attributes are derived and provided for informational purposes: <user_email>[email protected]</user_email> <task_name>Remove converter assembly</task_name> <sum_hours type="float">2.00</sum_hours> <budget type="float">10.00</budget> <project_name>Realign dilithium crystals</project_name> <client_name>Starfleet Command</client_name> </entry> </entries> Im assuming in this case that I dont necessarily care about all of the data fields the service is returning I just need some of them for my applications purposes.  Thus, you can see there are more elements in the <entry> XML than I have in my Entry class. Get The XML with C# The next step is to get the XML.  The following snippet does the heavy lifting once you pass it the appropriate URL: protected XElement GetResponse(string uri) { var request = WebRequest.Create(uri) as HttpWebRequest; request.UserAgent = ".NET Sample"; request.KeepAlive = false;   request.Timeout = 15 * 1000;   var response = request.GetResponse() as HttpWebResponse;   if (request.HaveResponse == true && response != null) { var reader = new StreamReader(response.GetResponseStream()); return XElement.Parse(reader.ReadToEnd()); } throw new Exception("Error fetching data."); } This is adapted from the Yahoo Developer article on Web Service REST calls.  Once you have the XML, the last step is to get the data back as your POCO. Use LINQ-To-XML to Deserialize POCOs from XML This is done via the following code: public IEnumerable<Entry> List(DateTime startDate, DateTime endDate) { string additionalParameters = String.Format("start_date={0}&end_date={1}", startDate.ToShortDateString(), endDate.ToShortDateString()); string uri = BuildUrl("entries", additionalParameters);   XElement elements = GetResponse(uri);   var entries = from e in elements.Elements() where e.Name.LocalName == "entry" select new Entry { Id = int.Parse(e.Element("id").Value), UserId = int.Parse(e.Element("user_id").Value), Date = DateTime.Parse(e.Element("date").Value), Hours = float.Parse(e.Element("hours").Value), Notes = e.Element("notes").Value, Billable = bool.Parse(e.Element("billable").Value) }; return entries; }   For completeness, heres the BuildUrl method for my TickSpot API wrapper: // Change these to your settings protected const string projectDomain = "DOMAIN.tickspot.com"; private const string authParams = "[email protected]&password=MyTickSpotPassword";   protected string BuildUrl(string apiMethod, string additionalParams) { if (projectDomain.Contains("DOMAIN")) { throw new ApplicationException("You must update your domain in ProjectRepository.cs."); } if (authParams.Contains("MyTickSpotPassword")) { throw new ApplicationException("You must update your email and password in ProjectRepository.cs."); } return string.Format("https://{0}/api/{1}?{2}&{3}", projectDomain, apiMethod, authParams, additionalParams); } Thats it!  Now go forth and consume XML and map it to classes you actually want to work with.  Have fun! Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

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