Search Results

Search found 211 results on 9 pages for 'httprequest'.

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

  • Reading HttpRequest Body in REST WCF

    - by madness800
    Hi All, I got a REST WCF Service running in .net 4 and I've tested the web service it is working and accepting HttpRequest I make to it. But I ran into a problem trying to access the HttpRequest body within the web service. I've tried sending random sizes of data appended on the HttpRequest using both Fiddler and my WinForm app and I can't seem to find any objects in runtime where I can find my request body is located. My initial instinct was to look in the HttpContext.Current.Request.InputStream but the length of that property is 0, so I tried looking in IncomingWebRequestContext that object doesn't even have a method nor properties to get the body of the HttpRequest. So my question is, is there actually a way to access the HttpRequest request body in WCF? PS: The data inside the request body is JSON strings and for response it would return the data inside response body as JSON string too.

    Read the article

  • Calling HttpRequest::getRawRequestMessage() without send()

    - by danielgrad
    I am trying to call getRawRequestMessage() to get the raw HTTP content of the request described by a HttpRequest object, but I notice it always returns an empty string if I don't call send() first. Which kind of defeats my purpose (I want to send the data through other means than the HttpRequest's own send() method). Is there any other way to convert a HttpRequest object to it's raw string equivalent? To give more context: I'm working with a complex class that builds a HttpRequest object and sends requests through it and I want to add a new mode to the class that will work through raw sockets instead. The request is already built in the HttpRequest object and I would like to not have to parse the object manually to generate the HTTP message.

    Read the article

  • PHP HttpRequest Cookie Issue

    - by Daaron
    I have a chunk of code to login to test a web site login: $r = new HttpRequest($newlocation, HttpRequest::METH_GET); $r-addCookies($cookieArray); $r-send(); The content of $cookieArray is from a redirect, but I don't modify it in any way. The really baked part is that if the value of the cookie (an authentication token string) contains a slash, it doesn't login properly. If it doesn't have a slash, everything works. Any ideas are appreciated.

    Read the article

  • C# HttpRequest - Accessing hashtags in url

    - by CloudyOne
    Unfortunately because of the wide use of the word "hashtag" and "httprequest" i couldn't find any search results that gave me an answer on whether something like this is even possible. If i have a url like this: /Orders/Product#12345 The HttpRequest class shows me that the FilePath, RawUrl, and all other members that show the url as /Orders/Product It just gets rid of the hashtag, and i can't find a place to view it. Is there any way for me to be able to see what hashtag is on the end of the URL from the codebehind? I know i could easily make this a QueryString parameter, but i like the way this looks better, so if there's a way to do it, i'd like to find out what it is :) Thanks in advance!

    Read the article

  • Understanding Request Validation in ASP.NET MVC 3

    - by imran_ku07
         Introduction:             A fact that you must always remember "never ever trust user inputs". An application that trusts user inputs may be easily vulnerable to XSS, XSRF, SQL Injection, etc attacks. XSS and XSRF are very dangerous attacks. So to mitigate these attacks ASP.NET introduced request validation in ASP.NET 1.1. During request validation, ASP.NET will throw HttpRequestValidationException: 'A potentially dangerous XXX value was detected from the client', if he found, < followed by an exclamation(like <!) or < followed by the letters a through z(like <s) or & followed by a pound sign(like &#123) as a part of query string, posted form and cookie collection. In ASP.NET 4.0, request validation becomes extensible. This means that you can extend request validation. Also in ASP.NET 4.0, by default request validation is enabled before the BeginRequest phase of an HTTP request. ASP.NET MVC 3 moves one step further by making request validation granular. This allows you to disable request validation for some properties of a model while maintaining request validation for all other cases. In this article I will show you the use of request validation in ASP.NET MVC 3. Then I will briefly explain the internal working of granular request validation.       Description:             First of all create a new ASP.NET MVC 3 application. Then create a simple model class called MyModel,     public class MyModel { public string Prop1 { get; set; } public string Prop2 { get; set; } }             Then just update the index action method as follows,   public ActionResult Index(MyModel p) { return View(); }             Now just run this application. You will find that everything works just fine. Now just append this query string ?Prop1=<s to the url of this application, you will get the HttpRequestValidationException exception.           Now just decorate the Index action method with [ValidateInputAttribute(false)],   [ValidateInput(false)] public ActionResult Index(MyModel p) { return View(); }             Run this application again with same query string. You will find that your application run without any unhandled exception.           Up to now, there is nothing new in ASP.NET MVC 3 because ValidateInputAttribute was present in the previous versions of ASP.NET MVC. Any problem with this approach? Yes there is a problem with this approach. The problem is that now users can send html for both Prop1 and Prop2 properties and a lot of developers are not aware of it. This means that now everyone can send html with both parameters(e.g, ?Prop1=<s&Prop2=<s). So ValidateInput attribute does not gives you the guarantee that your application is safe to XSS or XSRF. This is the reason why ASP.NET MVC team introduced granular request validation in ASP.NET MVC 3. Let's see this feature.           Remove [ValidateInputAttribute(false)] on Index action and update MyModel class as follows,   public class MyModel { [AllowHtml] public string Prop1 { get; set; } public string Prop2 { get; set; } }             Note that AllowHtml attribute is only decorated on Prop1 property. Run this application again with ?Prop1=<s query string. You will find that your application run just fine. Run this application again with ?Prop1=<s&Prop2=<s query string, you will get HttpRequestValidationException exception. This shows that the granular request validation in ASP.NET MVC 3 only allows users to send html for properties decorated with AllowHtml attribute.            Sometimes you may need to access Request.QueryString or Request.Form directly. You may change your code as follows,   [ValidateInput(false)] public ActionResult Index() { var prop1 = Request.QueryString["Prop1"]; return View(); }             Run this application again, you will get the HttpRequestValidationException exception again even you have [ValidateInput(false)] on your Index action. The reason is that Request flags are still not set to unvalidate. I will explain this later. For making this work you need to use Unvalidated extension method,     public ActionResult Index() { var q = Request.Unvalidated().QueryString; var prop1 = q["Prop1"]; return View(); }             Unvalidated extension method is defined in System.Web.Helpers namespace . So you need to add using System.Web.Helpers; in this class file. Run this application again, your application run just fine.             There you have it. If you are not curious to know the internal working of granular request validation then you can skip next paragraphs completely. If you are interested then carry on reading.             Create a new ASP.NET MVC 2 application, then open global.asax.cs file and the following lines,     protected void Application_BeginRequest() { var q = Request.QueryString; }             Then make the Index action method as,    [ValidateInput(false)] public ActionResult Index(string id) { return View(); }             Please note that the Index action method contains a parameter and this action method is decorated with [ValidateInput(false)]. Run this application again, but now with ?id=<s query string, you will get HttpRequestValidationException exception at Application_BeginRequest method. Now just add the following entry in web.config,   <httpRuntime requestValidationMode="2.0"/>             Now run this application again. This time your application will run just fine. Now just see the following quote from ASP.NET 4 Breaking Changes,   In ASP.NET 4, by default, request validation is enabled for all requests, because it is enabled before the BeginRequest phase of an HTTP request. As a result, request validation applies to requests for all ASP.NET resources, not just .aspx page requests. This includes requests such as Web service calls and custom HTTP handlers. Request validation is also active when custom HTTP modules are reading the contents of an HTTP request.             This clearly state that request validation is enabled before the BeginRequest phase of an HTTP request. For understanding what does enabled means here, we need to see HttpRequest.ValidateInput, HttpRequest.QueryString and HttpRequest.Form methods/properties in System.Web assembly. Here is the implementation of HttpRequest.ValidateInput, HttpRequest.QueryString and HttpRequest.Form methods/properties in System.Web assembly,     public NameValueCollection Form { get { if (this._form == null) { this._form = new HttpValueCollection(); if (this._wr != null) { this.FillInFormCollection(); } this._form.MakeReadOnly(); } if (this._flags[2]) { this._flags.Clear(2); this.ValidateNameValueCollection(this._form, RequestValidationSource.Form); } return this._form; } } public NameValueCollection QueryString { get { if (this._queryString == null) { this._queryString = new HttpValueCollection(); if (this._wr != null) { this.FillInQueryStringCollection(); } this._queryString.MakeReadOnly(); } if (this._flags[1]) { this._flags.Clear(1); this.ValidateNameValueCollection(this._queryString, RequestValidationSource.QueryString); } return this._queryString; } } public void ValidateInput() { if (!this._flags[0x8000]) { this._flags.Set(0x8000); this._flags.Set(1); this._flags.Set(2); this._flags.Set(4); this._flags.Set(0x40); this._flags.Set(0x80); this._flags.Set(0x100); this._flags.Set(0x200); this._flags.Set(8); } }             The above code indicates that HttpRequest.QueryString and HttpRequest.Form will only validate the querystring and form collection if certain flags are set. These flags are automatically set if you call HttpRequest.ValidateInput method. Now run the above application again(don't forget to append ?id=<s query string in the url) with the same settings(i.e, requestValidationMode="2.0" setting in web.config and Application_BeginRequest method in global.asax.cs), your application will run just fine. Now just update the Application_BeginRequest method as,   protected void Application_BeginRequest() { Request.ValidateInput(); var q = Request.QueryString; }             Note that I am calling Request.ValidateInput method prior to use Request.QueryString property. ValidateInput method will internally set certain flags(discussed above). These flags will then tells the Request.QueryString (and Request.Form) property that validate the query string(or form) when user call Request.QueryString(or Request.Form) property. So running this application again with ?id=<s query string will throw HttpRequestValidationException exception. Now I hope it is clear to you that what does requestValidationMode do. It just tells the ASP.NET that not invoke the Request.ValidateInput method internally before the BeginRequest phase of an HTTP request if requestValidationMode is set to a value less than 4.0 in web.config. Here is the implementation of HttpRequest.ValidateInputIfRequiredByConfig method which will prove this statement(Don't be confused with HttpRequest and Request. Request is the property of HttpRequest class),    internal void ValidateInputIfRequiredByConfig() { ............................................................... ............................................................... ............................................................... ............................................................... if (httpRuntime.RequestValidationMode >= VersionUtil.Framework40) { this.ValidateInput(); } }              Hopefully the above discussion will clear you how requestValidationMode works in ASP.NET 4. It is also interesting to note that both HttpRequest.QueryString and HttpRequest.Form only throws the exception when you access them first time. Any subsequent access to HttpRequest.QueryString and HttpRequest.Form will not throw any exception. Continuing with the above example, just update Application_BeginRequest method in global.asax.cs file as,   protected void Application_BeginRequest() { try { var q = Request.QueryString; var f = Request.Form; } catch//swallow this exception { } var q1 = Request.QueryString; var f1 = Request.Form; }             Without setting requestValidationMode to 2.0 and without decorating ValidateInput attribute on Index action, your application will work just fine because both HttpRequest.QueryString and HttpRequest.Form will clear their flags after reading HttpRequest.QueryString and HttpRequest.Form for the first time(see the implementation of HttpRequest.QueryString and HttpRequest.Form above).           Now let's see ASP.NET MVC 3 granular request validation internal working. First of all we need to see type of HttpRequest.QueryString and HttpRequest.Form properties. Both HttpRequest.QueryString and HttpRequest.Form properties are of type NameValueCollection which is inherited from the NameObjectCollectionBase class. NameObjectCollectionBase class contains _entriesArray, _entriesTable, NameObjectEntry.Key and NameObjectEntry.Value fields which granular request validation uses internally. In addition granular request validation also uses _queryString, _form and _flags fields, ValidateString method and the Indexer of HttpRequest class. Let's see when and how granular request validation uses these fields.           Create a new ASP.NET MVC 3 application. Then put a breakpoint at Application_BeginRequest method and another breakpoint at HomeController.Index method. Now just run this application. When the break point inside Application_BeginRequest method hits then add the following expression in quick watch window, System.Web.HttpContext.Current.Request.QueryString. You will see the following screen,                                              Now Press F5 so that the second breakpoint inside HomeController.Index method hits. When the second breakpoint hits then add the following expression in quick watch window again, System.Web.HttpContext.Current.Request.QueryString. You will see the following screen,                            First screen shows that _entriesTable field is of type System.Collections.Hashtable and _entriesArray field is of type System.Collections.ArrayList during the BeginRequest phase of the HTTP request. While the second screen shows that _entriesTable type is changed to Microsoft.Web.Infrastructure.DynamicValidationHelper.LazilyValidatingHashtable and _entriesArray type is changed to Microsoft.Web.Infrastructure.DynamicValidationHelper.LazilyValidatingArrayList during executing the Index action method. In addition to these members, ASP.NET MVC 3 also perform some operation on _flags, _form, _queryString and other members of HttpRuntime class internally. This shows that ASP.NET MVC 3 performing some operation on the members of HttpRequest class for making granular request validation possible.           Both LazilyValidatingArrayList and LazilyValidatingHashtable classes are defined in the Microsoft.Web.Infrastructure assembly. You may wonder why their name starts with Lazily. The fact is that now with ASP.NET MVC 3, request validation will be performed lazily. In simple words, Microsoft.Web.Infrastructure assembly is now taking the responsibility for request validation from System.Web assembly. See the below screens. The first screen depicting HttpRequestValidationException exception in ASP.NET MVC 2 application while the second screen showing HttpRequestValidationException exception in ASP.NET MVC 3 application.   In MVC 2:                 In MVC 3:                          The stack trace of the second screenshot shows that Microsoft.Web.Infrastructure assembly (instead of System.Web assembly) is now performing request validation in ASP.NET MVC 3. Now you may ask: where Microsoft.Web.Infrastructure assembly is performing some operation on the members of HttpRequest class. There are at least two places where the Microsoft.Web.Infrastructure assembly performing some operation , Microsoft.Web.Infrastructure.DynamicValidationHelper.GranularValidationReflectionUtil.GetInstance method and Microsoft.Web.Infrastructure.DynamicValidationHelper.ValidationUtility.CollectionReplacer.ReplaceCollection method, Here is the implementation of these methods,   private static GranularValidationReflectionUtil GetInstance() { try { if (DynamicValidationShimReflectionUtil.Instance != null) { return null; } GranularValidationReflectionUtil util = new GranularValidationReflectionUtil(); Type containingType = typeof(NameObjectCollectionBase); string fieldName = "_entriesArray"; bool isStatic = false; Type fieldType = typeof(ArrayList); FieldInfo fieldInfo = CommonReflectionUtil.FindField(containingType, fieldName, isStatic, fieldType); util._del_get_NameObjectCollectionBase_entriesArray = MakeFieldGetterFunc<NameObjectCollectionBase, ArrayList>(fieldInfo); util._del_set_NameObjectCollectionBase_entriesArray = MakeFieldSetterFunc<NameObjectCollectionBase, ArrayList>(fieldInfo); Type type6 = typeof(NameObjectCollectionBase); string str2 = "_entriesTable"; bool flag2 = false; Type type7 = typeof(Hashtable); FieldInfo info2 = CommonReflectionUtil.FindField(type6, str2, flag2, type7); util._del_get_NameObjectCollectionBase_entriesTable = MakeFieldGetterFunc<NameObjectCollectionBase, Hashtable>(info2); util._del_set_NameObjectCollectionBase_entriesTable = MakeFieldSetterFunc<NameObjectCollectionBase, Hashtable>(info2); Type targetType = CommonAssemblies.System.GetType("System.Collections.Specialized.NameObjectCollectionBase+NameObjectEntry"); Type type8 = targetType; string str3 = "Key"; bool flag3 = false; Type type9 = typeof(string); FieldInfo info3 = CommonReflectionUtil.FindField(type8, str3, flag3, type9); util._del_get_NameObjectEntry_Key = MakeFieldGetterFunc<string>(targetType, info3); Type type10 = targetType; string str4 = "Value"; bool flag4 = false; Type type11 = typeof(object); FieldInfo info4 = CommonReflectionUtil.FindField(type10, str4, flag4, type11); util._del_get_NameObjectEntry_Value = MakeFieldGetterFunc<object>(targetType, info4); util._del_set_NameObjectEntry_Value = MakeFieldSetterFunc(targetType, info4); Type type12 = typeof(HttpRequest); string methodName = "ValidateString"; bool flag5 = false; Type[] argumentTypes = new Type[] { typeof(string), typeof(string), typeof(RequestValidationSource) }; Type returnType = typeof(void); MethodInfo methodInfo = CommonReflectionUtil.FindMethod(type12, methodName, flag5, argumentTypes, returnType); util._del_validateStringCallback = CommonReflectionUtil.MakeFastCreateDelegate<HttpRequest, ValidateStringCallback>(methodInfo); Type type = CommonAssemblies.SystemWeb.GetType("System.Web.HttpValueCollection"); util._del_HttpValueCollection_ctor = CommonReflectionUtil.MakeFastNewObject<Func<NameValueCollection>>(type); Type type14 = typeof(HttpRequest); string str6 = "_form"; bool flag6 = false; Type type15 = type; FieldInfo info6 = CommonReflectionUtil.FindField(type14, str6, flag6, type15); util._del_get_HttpRequest_form = MakeFieldGetterFunc<HttpRequest, NameValueCollection>(info6); util._del_set_HttpRequest_form = MakeFieldSetterFunc(typeof(HttpRequest), info6); Type type16 = typeof(HttpRequest); string str7 = "_queryString"; bool flag7 = false; Type type17 = type; FieldInfo info7 = CommonReflectionUtil.FindField(type16, str7, flag7, type17); util._del_get_HttpRequest_queryString = MakeFieldGetterFunc<HttpRequest, NameValueCollection>(info7); util._del_set_HttpRequest_queryString = MakeFieldSetterFunc(typeof(HttpRequest), info7); Type type3 = CommonAssemblies.SystemWeb.GetType("System.Web.Util.SimpleBitVector32"); Type type18 = typeof(HttpRequest); string str8 = "_flags"; bool flag8 = false; Type type19 = type3; FieldInfo flagsFieldInfo = CommonReflectionUtil.FindField(type18, str8, flag8, type19); Type type20 = type3; string str9 = "get_Item"; bool flag9 = false; Type[] typeArray4 = new Type[] { typeof(int) }; Type type21 = typeof(bool); MethodInfo itemGetter = CommonReflectionUtil.FindMethod(type20, str9, flag9, typeArray4, type21); Type type22 = type3; string str10 = "set_Item"; bool flag10 = false; Type[] typeArray6 = new Type[] { typeof(int), typeof(bool) }; Type type23 = typeof(void); MethodInfo itemSetter = CommonReflectionUtil.FindMethod(type22, str10, flag10, typeArray6, type23); MakeRequestValidationFlagsAccessors(flagsFieldInfo, itemGetter, itemSetter, out util._del_BitVector32_get_Item, out util._del_BitVector32_set_Item); return util; } catch { return null; } } private static void ReplaceCollection(HttpContext context, FieldAccessor<NameValueCollection> fieldAccessor, Func<NameValueCollection> propertyAccessor, Action<NameValueCollection> storeInUnvalidatedCollection, RequestValidationSource validationSource, ValidationSourceFlag validationSourceFlag) { NameValueCollection originalBackingCollection; ValidateStringCallback validateString; SimpleValidateStringCallback simpleValidateString; Func<NameValueCollection> getActualCollection; Action<NameValueCollection> makeCollectionLazy; HttpRequest request = context.Request; Func<bool> getValidationFlag = delegate { return _reflectionUtil.GetRequestValidationFlag(request, validationSourceFlag); }; Func<bool> func = delegate { return !getValidationFlag(); }; Action<bool> setValidationFlag = delegate (bool value) { _reflectionUtil.SetRequestValidationFlag(request, validationSourceFlag, value); }; if ((fieldAccessor.Value != null) && func()) { storeInUnvalidatedCollection(fieldAccessor.Value); } else { originalBackingCollection = fieldAccessor.Value; validateString = _reflectionUtil.MakeValidateStringCallback(context.Request); simpleValidateString = delegate (string value, string key) { if (((key == null) || !key.StartsWith("__", StringComparison.Ordinal)) && !string.IsNullOrEmpty(value)) { validateString(value, key, validationSource); } }; getActualCollection = delegate { fieldAccessor.Value = originalBackingCollection; bool flag = getValidationFlag(); setValidationFlag(false); NameValueCollection col = propertyAccessor(); setValidationFlag(flag); storeInUnvalidatedCollection(new NameValueCollection(col)); return col; }; makeCollectionLazy = delegate (NameValueCollection col) { simpleValidateString(col[null], null); LazilyValidatingArrayList array = new LazilyValidatingArrayList(_reflectionUtil.GetNameObjectCollectionEntriesArray(col), simpleValidateString); _reflectionUtil.SetNameObjectCollectionEntriesArray(col, array); LazilyValidatingHashtable table = new LazilyValidatingHashtable(_reflectionUtil.GetNameObjectCollectionEntriesTable(col), simpleValidateString); _reflectionUtil.SetNameObjectCollectionEntriesTable(col, table); }; Func<bool> hasValidationFired = func; Action disableValidation = delegate { setValidationFlag(false); }; Func<int> fillInActualFormContents = delegate { NameValueCollection values = getActualCollection(); makeCollectionLazy(values); return values.Count; }; DeferredCountArrayList list = new DeferredCountArrayList(hasValidationFired, disableValidation, fillInActualFormContents); NameValueCollection target = _reflectionUtil.NewHttpValueCollection(); _reflectionUtil.SetNameObjectCollectionEntriesArray(target, list); fieldAccessor.Value = target; } }             Hopefully the above code will help you to understand the internal working of granular request validation. It is also important to note that Microsoft.Web.Infrastructure assembly invokes HttpRequest.ValidateInput method internally. For further understanding please see Microsoft.Web.Infrastructure assembly code. Finally you may ask: at which stage ASP NET MVC 3 will invoke these methods. You will find this answer by looking at the following method source,   Unvalidated extension method for HttpRequest class defined in System.Web.Helpers.Validation class. System.Web.Mvc.MvcHandler.ProcessRequestInit method. System.Web.Mvc.ControllerActionInvoker.ValidateRequest method. System.Web.WebPages.WebPageHttpHandler.ProcessRequestInternal method.       Summary:             ASP.NET helps in preventing XSS attack using a feature called request validation. In this article, I showed you how you can use granular request validation in ASP.NET MVC 3. I explain you the internal working of  granular request validation. Hope you will enjoy this article too.   SyntaxHighlighter.all()

    Read the article

  • Sending an image via POST Multipart (HTTPRequest)

    - by James Jeffery
    I'm trying to send an image to a server, using HTTP Post Multipart. Everything else is fine, I have all the boundrys set and stuff. But what do I have to do to the image before hand? Do I have to convert it to binary? Here is the header data from the header (using Fiddler). This is what I need to upload: -----------------------------7daea2aa40c80 Content-Disposition: form-data; name="pict"; filename="pic.jpeg" Content-Type: image/pjpeg <Binary here ... or at least I think it is> .. ?????JFIF?????????C? (lots more of this I removed) Any advice?

    Read the article

  • C# multiple asynchronous HttpRequest with one callback

    - by aepheus
    I want to make 10 asynchronous http requests at once and only process the results when all have completed and in a single callback function. I also do not want to block any threads using WaitAll (it is my understanding that WaitAll blocks until all are complete). I think I want to make a custom IAsyncResult which will handle multiple calls. Am I on the right track? Are there any good resources or examples out there that describe handling this?

    Read the article

  • .NET: What's the difference between HttpMethod and RequestType of HttpRequest?

    - by Ian Boyd
    The HttpRequest class defines two properties: HttpMethod: Gets the HTTP data transfer method (such as GET, POST, or HEAD) used by the client. public string HttpMethod { get; } The HTTP data transfer method used by the client. and RequestType: Gets or sets the HTTP data transfer method (GET or POST) used by the client. public string RequestType { get; set; } A string representing the HTTP invocation type sent by the client. What is the difference between these two properties? When would i want to use one over the other? Which is the proper one to inspect to see what data transfer method was used by the client? The documentation indicates that HttpMethod will return whatever verb was used: such as GET, POST, or HEAD while the documentation on RequestType seems to indicate only one of two possible values: GET or POST i test with a random sampling of verbs, and both properties seem to support all verbs, and both return the same values: Testing: Client Used HttpMethod RequestType GET GET GET POST POST POST HEAD HEAD HEAD CONNECT CONNECT CONNECT MKCOL MKCOL MKCOL PUT PUT PUT FOOTEST FOOTEST FOOTEST What is the difference between: HttpRequest.HttpMethod HttpRequest.RequestType and when should i use one over the other? Keywords: iis asp.net http httprequest httphandler

    Read the article

  • Blackberry Asynchronous HTTP Requests - How?

    - by Kai
    The app I'm working on has a self contained database. The only time I need HTTP request is when the user first loads the app. I do this by calling a class that verifies whether or not a local DB exists and, if not, create one with the following request: HttpRequest data = new HttpRequest("http://www.somedomain.com/xml", "GET", this); data.start(); This xml returns a list of content, all of which have images that I want to fetch AFTER the original request is complete and stored. So something like this won't work: HttpRequest data = new HttpRequest("http://www.somedomain.com/xml", "GET", this); data.start(); HttpRequest images = new HttpRequest("http://www.somedomain.com/xmlImages", "GET", this); images.start(); Since it will not treat this like an asynchronous request. I have not found much information on adding callbacks to httpRequest, or any other method I could use to ensure operation 2 does not execute until operation 1 is complete. Any help would be appreciated. Thanks

    Read the article

  • Webserver not giving the correct response on CURL and other httprequest methods [migrated]

    - by Maxim
    I am trying to make a REST request to a external webserver by using this code <?php $user = 'USER'; $pass = 'PASS'; $data = "MYDATA" $ch = curl_init('URL'); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data)) ); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_VERBOSE, true); if(!($res = curl_exec($ch))) { echo('[cURL Failure] ' . curl_error($ch)); } curl_close($ch); echo($res); Now this is a CURL request, however i tried different methods to test my result and they all give me a 403 forbidden error response that i get from the webserver, however i do get a 200 response when i run it on any other webserver (localhost, webserver2, ...) Therefore i think there is something wrong with my webserver and it might be disallowing/caching the post parameters that i provide because sometimes it returns a 200 response but most of the times it returns the 403. This is the response i get : HTTP/1.1 403 Forbidden Accept-Ranges: bytes Content-Type: application/json; charset=UTF-8 Date: Sat, 26 Oct 2013 13:56:37 GMT Server: Restlet-Framework/2.1.3 Vary: Accept-Charset, Accept-Encoding, Accept-Language, Accept Content-Length: 77 Connection: keep-alive {"error":"ForbiddenOperationException","errorMessage":"Invalid credentials."} It says Invalid credentials however i provide the correct credentials and i can confirm them because it is working on other servers. Since this is a crucial part of my script that i use for clients to register i assume that there is something wrong with the post parameters. I am running cpanel and uninstalled the following already: - varnish - apachebooster i also recompiled php already and enabled curl and its dependencies but nothing seems to resolve my problem. If more information is required then don't hesitate to ask me in the comments i will respond very quickly as i really need this. any help is appreciated. Kind regards Maxim

    Read the article

  • Windows Phone 7 HttpRequest Unable to see true Error Code and response details

    - by Bob
    I have to call a somewhat broken API from a Windows Phone 7 application. The API returns a 302 error and a cookie to the authentication request. I've tried every way I've been able to find in the MSDN documentation for using ClientHTTP instead of BrowserHTTP (registering the prefix, using the call to explicitly create a ClientHTTP using Request), but the 302 is getting translated to a 404 and I'm not seeing the cookies on the response. I've tried a WebClient, I've tried an HttpRequest and it is always the translated error message. If I allocate a CookieContainer for the HttpRequest, I get a null argument exception when the client stack is parsing the returned message. I can see that the response is coming back as expected via Fiddler.

    Read the article

  • Memory leak till crash due to HttpRequest

    - by Alex R.
    I played with HttpRequest and realized that the memory is not cleaned up after any request. After some time the running tab within Chrome will crash. Here is some testing code. Put a large sized file into the 'www' directory and set the URL in the code accordingly. import 'dart:async'; import 'dart:html'; void main() { const PATH = "http://127.0.0.1:3030/PATH_TO_FILE"; new Timer.periodic(new Duration(seconds:10), (Timer it)=>getString(PATH)); } void getString( String url){ HttpRequest.getString(url).then((String data){ }); } Is this really a bug or did I something wrong?

    Read the article

  • Android: How get the status-code of an HttpClient request

    - by Mannaz
    I want to download a file from and need to check the response status code (ie HTTP /1.1 200 OK). This is a snipped of my code: HttpGet httpRequest = new HttpGet(myUri); HttpEntity httpEntity = null; HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(httpRequest); ... How do i get the status-code of the response?

    Read the article

  • asp.net mvc rhino mocks mocking httprequest values

    - by Matthew
    Hi Is there a way to mock request params, what is the best approach when testing to create fake request values in order to run a test would some thing like this work? _context = MockRepository.GenerateStub<HttpContext>(); request = MockRepository.GenerateStub<HttpRequest>(); var collection = new NameValueCollection(); collection.Add("", ""); SetupResult.For(request.Params).Return(collection); SetupResult.For(_context.Request).Return(request);

    Read the article

  • Resolving HttpRequestScoped Instances outside of a HttpRequest in Autofac

    - by Page Brooks
    Suppose I have a dependency that is registered as HttpRequestScoped so there is only one instance per request. How could I resolve a dependency of the same type outside of an HttpRequest? For example: // Global.asax.cs Registration builder.Register(c => new MyDataContext(connString)).As<IDatabase>().HttpRequestScoped(); _containerProvider = new ContainerProvider(builder.Build()); // This event handler gets fired outside of a request // when a cached item is removed from the cache. public void CacheItemRemoved(string k, object v, CacheItemRemovedReason r) { // I'm trying to resolve like so, but this doesn't work... var dataContext = _containerProvider.ApplicationContainer.Resolve<IDatabase>(); // Do stuff with data context. } The above code throws a DependencyResolutionException when it executes the CacheItemRemoved handler: No scope matching the expression 'value(Autofac.Builder.RegistrationBuilder`3+<c__DisplayClass0[MyApp.Core.Data.MyDataContext,Autofac.Builder.SimpleActivatorData,Autofac.Builder.SingleRegistrationStyle]).lifetimeScopeTag.Equals(scope.Tag)' is visible from the scope in which the instance was requested.

    Read the article

  • Google slideshow shows a blank screen when calling from ajax

    - by ufk
    I'm having problems implementing google slideshow (http://www.google.com/uds/solutions/slideshow/index.html) to my web application by loading it using a jquery load() function. index.html: <script type="text/javascript" src="jquery-1.3.2.js"></script> <div id="moshe"></div> <script type="text/javascript"> $(document).ready(function(){ $('#moshe').load('test.html'); }); </script> test.html: <script type="text/javascript"> function load() { var samples = "http://dlc0421.googlepages.com/gfss.rss"; var options = { displayTime: 2000, transistionTime: 600, linkTarget : google.feeds.LINK_TARGET_BLANK }; new GFslideShow(samples, "slideshow", options); } google.load("feeds", "1"); google.setOnLoadCallback(load); </script> <div id="slideshow" class="gslideshow" style="width:300px;height:300px;position:relative; border: 2px solid blue">Loading...</div> When i execute the test.html, it loads the slideshow just fine. when i try to load using index.html that actually calls Jquery's $.load() function that loads the content of test.html into a specific div element, i see that the gallery is loading on that div, but when it's about to show images the entire page clears and all i have is a blank page. Any ideas ? a different version of index.html without using jquery: <script type="text/javascript"> function makeRequest(url) { var httpRequest; if (window.XMLHttpRequest) { // Mozilla, Safari, ... httpRequest = new XMLHttpRequest(); if (httpRequest.overrideMimeType) { httpRequest.overrideMimeType('text/xml'); // See note below about this line } } else if (window.ActiveXObject) { // IE try { httpRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} } } if (!httpRequest) { alert('Giving up :( Cannot create an XMLHTTP instance'); return false; } httpRequest.onreadystatechange = function() { alertContents(httpRequest); }; httpRequest.open('GET', url, true); httpRequest.send(''); } function alertContents(httpRequest) { if (httpRequest.readyState == 4) { if (httpRequest.status == 200) { document.getElementById('moshe').innerHTML=httpRequest.responseText; } else { alert('There was a problem with the request.'); } } } makeRequest('test.html'); </script>

    Read the article

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

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

    Read the article

  • HttpRequest.BeginWebRequest not executing asynchronously

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

    Read the article

  • [ASP.NET] Odd HttpRequest behaviour

    - by barguast
    I have a web service which runs with a HttpHandler class. In this class, I inspect the request stream for form / query string parameters. In some circumstances, it seemed as though these parameters weren't getting through. After a bit of digging around, I came across some behaviour I don't quite understand. See below: // The request contains 'a=1&b=2&c=3' // TEST ONLY: Read the entire request string contents; using (StreamReader sr = new StreamReader(context.Request.InputStream)) { contents = sr.ReadToEnd(); } // Here 'contents' is usually correct - containing 'a=1&b=2&c=3'. Sometimes it is empty. string a = context.Request["a"]; // Here, a = null, regardless of whether the 'contents' variable above is correct Can anyone explain to me why this might be happening? I'm using a .NET WebClient and UploadDataAsync to perform the request on the client if that makes any difference. If you need any more information, please let me know.

    Read the article

  • httprequest handle time delays till having response

    - by bourax webmaster
    I have an application that calls a function to send JSON object to a REST API, my problem is how can I handle time delays and repeat this function till i have a response from the server in case of interrupted network connexion ?? I try to use the Handler but i don't know how to stop it when i get a response !!! here's my function that is called when button clicked : protected void sendJson(final String name, final String email, final String homepage,final Long unixTime,final String bundleId) { Thread t = new Thread() { public void run() { Looper.prepare(); //For Preparing Message Pool for the child Thread HttpClient client = new DefaultHttpClient(); HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit HttpResponse response; JSONObject json = new JSONObject(); //creating meta object JSONObject metaJson = new JSONObject(); try { HttpPost post = new HttpPost("http://util.trademob.com:5000/cards"); metaJson.put("time", unixTime); metaJson.put("bundleId", bundleId); json.put("name", name); json.put("email", email); json.put("homepage", homepage); //add the meta in the root object json.put("meta", metaJson); StringEntity se = new StringEntity( json.toString()); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); post.setEntity(se); String authorizationString = "Basic " + Base64.encodeToString( ("tester" + ":" + "tm-sdktest").getBytes(), Base64.NO_WRAP); //Base64.NO_WRAP flag post.setHeader("Authorization", authorizationString); response = client.execute(post); String temp = EntityUtils.toString(response.getEntity()); Toast.makeText(getApplicationContext(), temp, Toast.LENGTH_LONG).show(); } catch(Exception e) { e.printStackTrace(); } Looper.loop(); //Loop in the message queue } }; t.start(); }

    Read the article

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