public RequestData <StreamList> Streams(string username) { var requestUrl = "https://api.twitch.tv/kraken/streams/followed"; var response = HttpWebRequestWrapper.ExecuteWebRequest(requestUrl, OAuthData.token); if (response.StatusCode != HttpStatusCode.OK) { var responseError = HttpWebRequestWrapper.ParseResponse <RequestErrorMessage>(response.ResponseString); return(new RequestData <StreamList>(responseError)); } var responseData = HttpWebRequestWrapper.ParseResponse <StreamList>(response.ResponseString); if (responseData != null && responseData.Total > 0) { var total = responseData.Total; var current = responseData.Streams.Count; var nexturl = responseData.Links.Next; do { var nextLinks = NextStreams(nexturl); responseData.Streams.AddRange(nextLinks.Data.Streams); nexturl = nextLinks.Data.Links.Next; current += nextLinks.Data.Streams.Count; } while (total > current); } return(new RequestData <StreamList>(responseData)); }
[Ignore] // This test requires TestService to run in a non-WinRT app. The code can be found in tests\Test.ADAL.NET.Unit\UnitTests.cs public async Task TimeoutTest() { const string TestServiceUrl = "http://localhost:8080"; HttpWebRequestWrapper webRequest = new HttpWebRequestWrapper(TestServiceUrl + "?delay=0&response_code=200") { TimeoutInMilliSeconds = 10000 }; await webRequest.GetResponseSyncOrAsync(new CallState(Guid.NewGuid(), false)); // Asynchronous try { webRequest = new HttpWebRequestWrapper(TestServiceUrl + "?delay=0&response_code=400") { TimeoutInMilliSeconds = 10000 }; await webRequest.GetResponseSyncOrAsync(new CallState(Guid.NewGuid(), false)); } catch (WebException ex) { Verify.AreEqual((int)(ex.Status), 7); // ProtocolError } try { webRequest = new HttpWebRequestWrapper(TestServiceUrl + "?delay=10000&response_code=200") { TimeoutInMilliSeconds = 500 }; await webRequest.GetResponseSyncOrAsync(new CallState(Guid.NewGuid(), false)); // Asynchronous } catch (WebException ex) { Verify.AreEqual((int)(ex.Status), 6); // RequestCanceled } }
public void When_Request_Method_Is_POST_Then_Request_Body_Contains_Encoded_Parameters() { string body = "Foo=12345&Bar=abcde"; var sourcebytes = Encoding.UTF8.GetBytes(body); client = new RestClient(); client.BaseUrl = BASE_URL; var request = new RestRequest(); request.Method = "POST"; request.AddParameter("Foo", "12345"); request.AddParameter("Bar", "abcde"); var wrapper = new HttpWebRequestWrapper(); wrapper.Request = new FakeHttpWebRequest(); var webrequest = (FakeHttpWebRequest)wrapper.ConfigureRequest(client, request); var stream = webrequest.GetRequestStream(); stream.Position = 0; byte[] actualbytes = stream.ReadAsBytes(); Assert.AreEqual(sourcebytes.Length, webrequest.ContentLength); Assert.AreEqual(sourcebytes.Length, actualbytes.Length); CollectionAssert.AreEquivalent(sourcebytes, actualbytes); }
public async Task TimeoutTest() { const string TestServiceUrl = "http://localhost:8080"; using (WebApp.Start <TestService>(TestServiceUrl)) { HttpWebRequestWrapper webRequest = new HttpWebRequestWrapper(TestServiceUrl + "?delay=0&response_code=200") { TimeoutInMilliSeconds = 10000 }; await webRequest.GetResponseSyncOrAsync(new CallState(Guid.NewGuid(), true)); // Synchronous webRequest = new HttpWebRequestWrapper(TestServiceUrl + "?delay=0&response_code=200") { TimeoutInMilliSeconds = 10000 }; await webRequest.GetResponseSyncOrAsync(new CallState(Guid.NewGuid(), false)); // Asynchronous try { webRequest = new HttpWebRequestWrapper(TestServiceUrl + "?delay=0&response_code=400") { TimeoutInMilliSeconds = 10000 }; await webRequest.GetResponseSyncOrAsync(new CallState(Guid.NewGuid(), false)); } catch (WebException ex) { Verify.AreEqual(ex.Status, WebExceptionStatus.ProtocolError); } try { webRequest = new HttpWebRequestWrapper(TestServiceUrl + "?delay=10000&response_code=200") { TimeoutInMilliSeconds = 500 }; await webRequest.GetResponseSyncOrAsync(new CallState(Guid.NewGuid(), true)); // Synchronous } catch (WebException ex) { Verify.AreEqual(ex.Status, WebExceptionStatus.Timeout); } try { webRequest = new HttpWebRequestWrapper(TestServiceUrl + "?delay=10000&response_code=200") { TimeoutInMilliSeconds = 500 }; await webRequest.GetResponseSyncOrAsync(new CallState(Guid.NewGuid(), false)); // Asynchronous } catch (WebException ex) { Verify.AreEqual(ex.Status, WebExceptionStatus.RequestCanceled); } } }
private AuthToken GetToken() { var request = new GetAuthTokenRequest(this.Serializer, TenantId, ClientId, ClientSecret); var webRequest = new HttpWebRequestWrapper(request.ApiEndpoint); return(request.Execute(webRequest)); }
static void Main(string[] args) { FacebookClient client = new FacebookClient(); HttpWebRequest request = HttpWebRequest.CreateHttp("https://www.facebook.com/m.tekeraslan"); Facebook.HttpWebRequestWrapper wrapper = new HttpWebRequestWrapper(request); var response = wrapper.GetResponse(); }
public void invalidBody() { // VEN2a ven = new VEN2a(new HttpWebRequestWrapper(), m_url, "TH_VEN", "password"); HttpWebRequestWrapper wr = new HttpWebRequestWrapper(false, System.Net.SecurityProtocolType.Tls12); wr.setAuthHeader("asdf"); wr.post(m_url + "/EiEvent", "application/xml", ""); }
public void CanCastToAHttpWebRequest() { // ARRANGE var creator = new HttpWebRequestWrapper(new Uri("http://fakeSite.fake")); // ACT var httpWebRequest = creator as System.Net.HttpWebRequest; // ASSET httpWebRequest.ShouldNotBeNull(); }
public void When_Request_Method_Is_POST_Then_ContentType_Is_FormEncoded() { var request = new RestRequest(); request.Method = "POST"; request.AddParameter("Foo", "12345"); request.AddParameter("Bar", "abcde"); var wrapper = new HttpWebRequestWrapper(); var webrequest = wrapper.ConfigureRequest(client, request); Assert.AreEqual("application/x-www-form-urlencoded", webrequest.ContentType); }
public void When_Http_Request_Times_Out_Then_Populate_Exception_Properties() { var message = "The operation has timed out"; var webexception = new WebException(message, null, WebExceptionStatus.Timeout, null); var wrapper = new HttpWebRequestWrapper(); var restresponse = wrapper.ParseWebException(webexception); Assert.IsNotNull(restresponse.ErrorException); Assert.AreEqual(message, restresponse.ErrorMessage); Assert.AreEqual(ResponseStatus.Error, restresponse.ResponseStatus); }
public void When_Request_Method_Is_GET_Then_ContentType_Is_Empty() { var request = new RestRequest(); request.Method = "GET"; request.AddParameter("Foo", "12345"); request.AddParameter("Bar", "abcde"); var wrapper = new HttpWebRequestWrapper(); var webrequest = wrapper.ConfigureRequest(client, request); Assert.IsTrue(string.IsNullOrWhiteSpace(webrequest.ContentType)); }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); FacebookClient.SetDefaultHttpWebRequestFactory(url => { var request = new HttpWebRequestWrapper((HttpWebRequest)WebRequest.Create(url)); request.Timeout = 1000 * 60 * 60; return(request); }); Application.Run(new FormMainConverter()); }
public RequestData <FollowList> Follows(string username) { var requestUrl = "https://api.twitch.tv/kraken/users/" + username + "/follows/channels"; var response = HttpWebRequestWrapper.ExecuteWebRequest(requestUrl, OAuthData.token); if (response.StatusCode != HttpStatusCode.OK) { var responseError = HttpWebRequestWrapper.ParseResponse <RequestErrorMessage>(response.ResponseString); return(new RequestData <FollowList>(responseError)); } var responseData = HttpWebRequestWrapper.ParseResponse <FollowList>(response.ResponseString); return(new RequestData <FollowList>(responseData)); }
public RequestData <StreamList> NextStreams(string url) { var requestUrl = url; var response = HttpWebRequestWrapper.ExecuteWebRequest(requestUrl, OAuthData.token); if (response.StatusCode != HttpStatusCode.OK) { var responseError = HttpWebRequestWrapper.ParseResponse <RequestErrorMessage>(response.ResponseString); return(new RequestData <StreamList>(responseError)); } var responseData = HttpWebRequestWrapper.ParseResponse <StreamList>(response.ResponseString); return(new RequestData <StreamList>(responseData)); }
public void When_Http_Request_Completes_Successfully_Then_Extract_Response() { var sourcecontent = Encoding.ASCII.GetBytes("{\"sid\": \"SMb2628b9fb5992e2f117891601451084b\", \"date_created\": \"Thu, 03 Apr 2014 02:11:55 +0000\", \"date_updated\": \"Thu, 03 Apr 2014 02:11:58 +0000\", \"date_sent\": \"Thu, 03 Apr 2014 02:11:58 +0000\", \"account_sid\": \"AC3137d76457814a5eabf7de62f346d39a\", \"to\": \"+13144586142\", \"from\": \"+19108638087\", \"body\": \"Enter '1234' to confirm your identity and access your account.\", \"status\": \"delivered\", \"num_segments\": \"1\", \"num_media\": null, \"direction\": \"outbound-api\", \"api_version\": \"2010-04-01\", \"price\": \"-0.00750\", \"price_unit\": \"USD\", \"uri\": \"/2010-04-01/Accounts/AC3137d76457814a5eabf7de62f346d39a/Messages/SMb2628b9fb5992e2f117891601451084b.json\", \"subresource_uris\": {\"media\": \"/2010-04-01/Accounts/AC3137d76457814a5eabf7de62f346d39a/Messages/SMb2628b9fb5992e2f117891601451084b/Media.json\"}}"); var stream = new MemoryStream(sourcecontent); FakeHttpWebResponse.InitializeHttpWebResponse(HttpStatusCode.OK, "OK", (int)sourcecontent.Length); var webresponse = new FakeHttpWebResponse(stream); var wrapper = new HttpWebRequestWrapper(); var restresponse = wrapper.ExtractResponse(webresponse); Assert.AreEqual(HttpStatusCode.OK, restresponse.StatusCode); Assert.AreEqual((int)sourcecontent.Length, restresponse.RawBytes.Length); CollectionAssert.AreEquivalent(sourcecontent, restresponse.RawBytes); }
public void When_Async_Http_Request_Is_Aborted_Then_Populate_Exception_Properties() { var message = "The request was aborted: The request was canceled."; var webexception = new WebException(message, null, WebExceptionStatus.RequestCanceled, null); var wrapper = new HttpWebRequestWrapper(); var restresponse = wrapper.ParseWebException(webexception, new TimeOutState() { TimedOut = false }); Assert.IsNotNull(restresponse.ErrorException); Assert.AreEqual(message, restresponse.ErrorMessage); Assert.AreEqual(ResponseStatus.Aborted, restresponse.ResponseStatus); }
public void When_Http_Protocol_Error_Then_Response_Contains_Status_Code_And_Description() { FakeHttpWebResponse.InitializeHttpWebResponse(HttpStatusCode.BadRequest, "BAD REQUEST"); var webexception = new WebException( "The remote server returned an error: (400) Bad Request.", null, WebExceptionStatus.ProtocolError, new FakeHttpWebResponse(new MemoryStream()) ); var wrapper = new HttpWebRequestWrapper(); var restresponse = wrapper.ParseWebException(webexception); Assert.AreEqual(HttpStatusCode.BadRequest, restresponse.StatusCode); Assert.AreEqual("BAD REQUEST", restresponse.StatusDescription); Assert.AreEqual(ResponseStatus.Completed, restresponse.ResponseStatus); }
protected virtual IHttpWebRequestWrapper GetRequestWrapper(string endpoint, int timeout, Dictionary<string, string> headers) { IHttpWebRequestWrapper request = new HttpWebRequestWrapper(endpoint) { Timeout = timeout }; if (headers != null && headers.Count > 0) { foreach (KeyValuePair<string, string> header in headers) { request.AddHeader(header.Key, header.Value); } } return request; }
static void Main(string[] args) { string url = "https://popl21.sigplan.org/"; HttpWebRequestWrapper newHttpWebRequestWrapper = new HttpWebRequestWrapper(url, 100); newHttpWebRequestWrapper.GetRequestStreamAsync(); NameValueCollection nvc = new NameValueCollection(); newHttpWebRequestWrapper.WriteParameterAsync(nvc); string fileStreamName = "file"; Stream newfilestream = File.OpenRead(fileStreamName); newHttpWebRequestWrapper.WriteStreamAsync(newfilestream, fileStreamName); newHttpWebRequestWrapper.WriteEndBoundaryAsync(); }
public void When_A_Default_Header_Is_Present_Then_WebRequest_Includes_This_Header() { string token = AuthorizationToken; client = new RestClient(); client.BaseUrl = BASE_URL; client.DefaultParameters.Add(new Parameter() { Name = "Authorization", Value = token, Type = ParameterType.HttpHeader }); var request = new RestRequest(); var wrapper = new HttpWebRequestWrapper(); var webrequest = wrapper.ConfigureRequest(client, request); Assert.IsTrue(webrequest.Headers.AllKeys.Contains("Authorization")); Assert.AreEqual(token, webrequest.Headers["Authorization"]); }
private RequestData <User> ValidateUsername(string username) { var response = HttpWebRequestWrapper.ExecuteWebRequest("https://api.twitch.tv/kraken/users/" + username); while (response.StatusCode == HttpStatusCode.Redirect || response.StatusCode == HttpStatusCode.RedirectKeepVerb) { response = HttpWebRequestWrapper.ExecuteWebRequest(response.RedirectUri.AbsolutePath); } if (response.StatusCode != HttpStatusCode.OK) { var responseError = HttpWebRequestWrapper.ParseResponse <User>(response.ResponseString); return(new RequestData <User>(responseError)); } var responseData = HttpWebRequestWrapper.ParseResponse <User>(response.ResponseString); return(new RequestData <User>(responseData)); }
public void When_Http_Protocol_Error_Then_Response_Contains_Content() { var sourcecontent = Encoding.ASCII.GetBytes("{\"code\": 90011, \"message\": \"Param From must be specified.\", \"more_info\": \"https://www.twilio.com/docs/errors/90011\", \"status\": 400}"); var stream = new MemoryStream(sourcecontent); FakeHttpWebResponse.InitializeHttpWebResponse(HttpStatusCode.BadRequest, "BAD REQUEST", (int)sourcecontent.Length); var webexception = new WebException( "The remote server returned an error: (400) Bad Request.", null, WebExceptionStatus.ProtocolError, new FakeHttpWebResponse(stream) ); var wrapper = new HttpWebRequestWrapper(); var restresponse = wrapper.ParseWebException(webexception); Assert.AreEqual(HttpStatusCode.BadRequest, restresponse.StatusCode); Assert.AreEqual((int)sourcecontent.Length, restresponse.RawBytes.Length); CollectionAssert.AreEquivalent(sourcecontent, restresponse.RawBytes); Assert.AreEqual(ResponseStatus.Completed, restresponse.ResponseStatus); }
public void When_Request_Method_Is_GET_Then_Request_Body_Does_Not_Contain_Encoded_Parameters() { byte[] sourcebytes = new byte[0]; var request = new RestRequest(); request.Method = "GET"; request.AddParameter("Foo", "12345"); request.AddParameter("Bar", "abcde"); var wrapper = new HttpWebRequestWrapper(); wrapper.Request = new FakeHttpWebRequest(); var webrequest = (FakeHttpWebRequest)wrapper.ConfigureRequest(client, request); var stream = webrequest.GetRequestStream(); byte[] actualbytes = stream.ReadAsBytes(); Assert.AreEqual(0, webrequest.ContentLength); Assert.AreEqual(sourcebytes.Length, actualbytes.Length); CollectionAssert.AreEquivalent(sourcebytes, actualbytes); }
protected virtual void ApiAsync(HttpMethod httpMethod, string path, object parameters, Type resultType, object userState) { Stream input; bool containsEtag; IList<int> batchEtags = null; var httpHelper = PrepareRequest(httpMethod, path, parameters, resultType, out input, out containsEtag, out batchEtags); _httpWebRequest = httpHelper.HttpWebRequest; #if FLUENTHTTP_CORE_TPL if (HttpWebRequestWrapperCreated != null) HttpWebRequestWrapperCreated(this, new HttpWebRequestCreatedEventArgs(userState, httpHelper.HttpWebRequest)); #endif var uploadProgressChanged = UploadProgressChanged; bool notifyUploadProgressChanged = uploadProgressChanged != null && httpHelper.HttpWebRequest.Method == "POST"; httpHelper.OpenReadCompleted += (o, e) => { FuntownApiEventArgs args; if (e.Cancelled) { args = new FuntownApiEventArgs(e.Error, true, userState, null); } else if (e.Error == null) { string responseString = null; try { using (var stream = e.Result) { #if NETFX_CORE bool compressed = false; var contentEncoding = httpHelper.HttpWebResponse.Headers.AllKeys.Contains("Content-Encoding") ? httpHelper.HttpWebResponse.Headers["Content-Encoding"] : null; if (contentEncoding != null) { if (contentEncoding.IndexOf("gzip") != -1) { using (var uncompressedStream = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionMode.Decompress)) { using (var reader = new StreamReader(uncompressedStream)) { responseString = reader.ReadToEnd(); } } compressed = true; } else if (contentEncoding.IndexOf("deflate") != -1) { using (var uncompressedStream = new System.IO.Compression.DeflateStream(stream, System.IO.Compression.CompressionMode.Decompress)) { using (var reader = new StreamReader(uncompressedStream)) { responseString = reader.ReadToEnd(); } } compressed = true; } } if (!compressed) { using (var reader = new StreamReader(stream)) { responseString = reader.ReadToEnd(); } } #else var response = httpHelper.HttpWebResponse; if (response != null && response.StatusCode == HttpStatusCode.NotModified) { var jsonObject = new JsonObject(); var headers = new JsonObject(); foreach (var headerName in response.Headers.AllKeys) headers[headerName] = response.Headers[headerName]; jsonObject["headers"] = headers; args = new FuntownApiEventArgs(null, false, userState, jsonObject); OnCompleted(httpMethod, args); return; } using (var reader = new StreamReader(stream)) { responseString = reader.ReadToEnd(); } #endif } try { object result = ProcessResponse(httpHelper, responseString, resultType, containsEtag, batchEtags); args = new FuntownApiEventArgs(null, false, userState, result); } catch (Exception ex) { args = new FuntownApiEventArgs(ex, false, userState, null); } } catch (Exception ex) { args = httpHelper.HttpWebRequest.IsCancelled ? new FuntownApiEventArgs(ex, true, userState, null) : new FuntownApiEventArgs(ex, false, userState, null); } } else { var webEx = e.Error as WebExceptionWrapper; if (webEx == null) { args = new FuntownApiEventArgs(e.Error, httpHelper.HttpWebRequest.IsCancelled, userState, null); } else { if (webEx.GetResponse() == null) { args = new FuntownApiEventArgs(webEx, false, userState, null); } else { var response = httpHelper.HttpWebResponse; if (response.StatusCode == HttpStatusCode.NotModified) { var jsonObject = new JsonObject(); var headers = new JsonObject(); foreach (var headerName in response.Headers.AllKeys) headers[headerName] = response.Headers[headerName]; jsonObject["headers"] = headers; args = new FuntownApiEventArgs(null, false, userState, jsonObject); } else { httpHelper.OpenReadAsync(); return; } } } } OnCompleted(httpMethod, args); }; if (input == null) { httpHelper.OpenReadAsync(); } else { // we have a request body so write httpHelper.OpenWriteCompleted += (o, e) => { FuntownApiEventArgs args; if (e.Cancelled) { input.Dispose(); args = new FuntownApiEventArgs(e.Error, true, userState, null); } else if (e.Error == null) { try { using (var stream = e.Result) { // write input to requestStream var buffer = new byte[BufferSize]; int nread; if (notifyUploadProgressChanged) { long totalBytesToSend = input.Length; long bytesSent = 0; while ((nread = input.Read(buffer, 0, buffer.Length)) != 0) { stream.Write(buffer, 0, nread); stream.Flush(); // notify upload progress changed bytesSent += nread; OnUploadProgressChanged(new FuntownUploadProgressChangedEventArgs(0, 0, bytesSent, totalBytesToSend, ((int)(bytesSent * 100 / totalBytesToSend)), userState)); } } else { while ((nread = input.Read(buffer, 0, buffer.Length)) != 0) { stream.Write(buffer, 0, nread); stream.Flush(); } } } httpHelper.OpenReadAsync(); return; } catch (Exception ex) { args = new FuntownApiEventArgs(ex, httpHelper.HttpWebRequest.IsCancelled, userState, null); } finally { input.Dispose(); } } else { input.Dispose(); var webExceptionWrapper = e.Error as WebExceptionWrapper; if (webExceptionWrapper != null) { var ex = webExceptionWrapper; if (ex.GetResponse() != null) { httpHelper.OpenReadAsync(); return; } } args = new FuntownApiEventArgs(e.Error, false, userState, null); } OnCompleted(httpMethod, args); }; httpHelper.OpenWriteAsync(); } }
protected virtual Task <object> ApiTaskAsync(HttpMethod httpMethod, string path, object parameters, Type resultType, object userState, CancellationToken cancellationToken #if ASYNC_AWAIT , IProgress <FacebookUploadProgressChangedEventArgs> uploadProgress #endif ) { var tcs = new TaskCompletionSource <object>(userState); if (cancellationToken.IsCancellationRequested) { tcs.TrySetCanceled(); return(tcs.Task); } HttpWebRequestWrapper httpWebRequest = null; EventHandler <HttpWebRequestCreatedEventArgs> httpWebRequestCreatedHandler = null; httpWebRequestCreatedHandler += (o, e) => { if (e.UserState != tcs) { return; } httpWebRequest = e.HttpWebRequest; }; var ctr = cancellationToken.Register(() => { try { if (httpWebRequest != null) { httpWebRequest.Abort(); } } catch { } }); #if ASYNC_AWAIT EventHandler <FacebookUploadProgressChangedEventArgs> uploadProgressHandler = null; if (uploadProgress != null) { uploadProgressHandler = (sender, e) => { if (e.UserState != tcs) { return; } uploadProgress.Report(new FacebookUploadProgressChangedEventArgs(e.BytesReceived, e.TotalBytesToReceive, e.BytesSent, e.TotalBytesToSend, e.ProgressPercentage, userState)); }; UploadProgressChanged += uploadProgressHandler; } #endif EventHandler <FacebookApiEventArgs> handler = null; handler = (sender, e) => { TransferCompletionToTask(tcs, e, e.GetResultData, () => { if (ctr != null) { ctr.Dispose(); } RemoveTaskAsyncHandlers(httpMethod, handler); HttpWebRequestWrapperCreated -= httpWebRequestCreatedHandler; #if ASYNC_AWAIT if (uploadProgressHandler != null) { UploadProgressChanged -= uploadProgressHandler; } #endif }); }; if (httpMethod == HttpMethod.Get) { GetCompleted += handler; } else if (httpMethod == HttpMethod.Post) { PostCompleted += handler; } else if (httpMethod == HttpMethod.Delete) { DeleteCompleted += handler; } else { throw new ArgumentOutOfRangeException("httpMethod"); } HttpWebRequestWrapperCreated += httpWebRequestCreatedHandler; try { ApiAsync(httpMethod, path, parameters, resultType, tcs); } catch { RemoveTaskAsyncHandlers(httpMethod, handler); HttpWebRequestWrapperCreated -= httpWebRequestCreatedHandler; #if ASYNC_AWAIT if (uploadProgressHandler != null) { UploadProgressChanged -= uploadProgressHandler; } #endif throw; } return(tcs.Task); }
public DefaultHttpRequestWrapper(WebClientWithTimeout client, string path) { this.method = HttpMethod.Get; httpWebRequestWrapper = HttpWebRequestWrapper.Create(client, path); }
//[Obsolete("Use ApiTaskAsync instead.")] //[EditorBrowsable(EditorBrowsableState.Never)] #endif protected virtual void ApiAsync(HttpMethod httpMethod, string path, object parameters, Type resultType, object userState) { Stream input; bool containsEtag; IList <int> batchEtags = null; var httpHelper = PrepareRequest(httpMethod, path, parameters, resultType, out input, out containsEtag, out batchEtags); _httpWebRequest = httpHelper.HttpWebRequest; #if FLUENTHTTP_CORE_TPL if (HttpWebRequestWrapperCreated != null) { HttpWebRequestWrapperCreated(this, new HttpWebRequestCreatedEventArgs(userState, httpHelper.HttpWebRequest)); } #endif var uploadProgressChanged = UploadProgressChanged; bool notifyUploadProgressChanged = uploadProgressChanged != null && httpHelper.HttpWebRequest.Method == "POST"; httpHelper.OpenReadCompleted += (o, e) => { FacebookApiEventArgs args; if (e.Cancelled) { args = new FacebookApiEventArgs(e.Error, true, userState, null); } else if (e.Error == null) { string responseString = null; try { using (var stream = e.Result) { #if NETFX_CORE bool compressed = false; var contentEncoding = httpHelper.HttpWebResponse.Headers.AllKeys.Contains("Content-Encoding") ? httpHelper.HttpWebResponse.Headers["Content-Encoding"] : null; if (contentEncoding != null) { if (contentEncoding.IndexOf("gzip") != -1) { using (var uncompressedStream = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionMode.Decompress)) { using (var reader = new StreamReader(uncompressedStream)) { responseString = reader.ReadToEnd(); } } compressed = true; } else if (contentEncoding.IndexOf("deflate") != -1) { using (var uncompressedStream = new System.IO.Compression.DeflateStream(stream, System.IO.Compression.CompressionMode.Decompress)) { using (var reader = new StreamReader(uncompressedStream)) { responseString = reader.ReadToEnd(); } } compressed = true; } } if (!compressed) { using (var reader = new StreamReader(stream)) { responseString = reader.ReadToEnd(); } } #else var response = httpHelper.HttpWebResponse; if (response != null && response.StatusCode == HttpStatusCode.NotModified) { var jsonObject = new JsonObject(); var headers = new JsonObject(); foreach (var headerName in response.Headers.AllKeys) { headers[headerName] = response.Headers[headerName]; } jsonObject["headers"] = headers; args = new FacebookApiEventArgs(null, false, userState, jsonObject); OnCompleted(httpMethod, args); return; } using (var reader = new StreamReader(stream)) { responseString = reader.ReadToEnd(); } #endif } try { object result = ProcessResponse(httpHelper, responseString, resultType, containsEtag, batchEtags); args = new FacebookApiEventArgs(null, false, userState, result); } catch (Exception ex) { args = new FacebookApiEventArgs(ex, false, userState, null); } } catch (Exception ex) { args = httpHelper.HttpWebRequest.IsCancelled ? new FacebookApiEventArgs(ex, true, userState, null) : new FacebookApiEventArgs(ex, false, userState, null); } } else { var webEx = e.Error as WebExceptionWrapper; if (webEx == null) { args = new FacebookApiEventArgs(e.Error, httpHelper.HttpWebRequest.IsCancelled, userState, null); } else { if (webEx.GetResponse() == null) { args = new FacebookApiEventArgs(webEx, false, userState, null); } else { var response = httpHelper.HttpWebResponse; if (response.StatusCode == HttpStatusCode.NotModified) { var jsonObject = new JsonObject(); var headers = new JsonObject(); foreach (var headerName in response.Headers.AllKeys) { headers[headerName] = response.Headers[headerName]; } jsonObject["headers"] = headers; args = new FacebookApiEventArgs(null, false, userState, jsonObject); } else { httpHelper.OpenReadAsync(); return; } } } } OnCompleted(httpMethod, args); }; if (input == null) { httpHelper.OpenReadAsync(); } else { // we have a request body so write httpHelper.OpenWriteCompleted += (o, e) => { FacebookApiEventArgs args; if (e.Cancelled) { input.Dispose(); args = new FacebookApiEventArgs(e.Error, true, userState, null); } else if (e.Error == null) { try { using (var stream = e.Result) { // write input to requestStream var buffer = new byte[BufferSize]; int nread; if (notifyUploadProgressChanged) { long totalBytesToSend = input.Length; long bytesSent = 0; while ((nread = input.Read(buffer, 0, buffer.Length)) != 0) { stream.Write(buffer, 0, nread); stream.Flush(); // notify upload progress changed bytesSent += nread; OnUploadProgressChanged(new FacebookUploadProgressChangedEventArgs(0, 0, bytesSent, totalBytesToSend, ((int)(bytesSent * 100 / totalBytesToSend)), userState)); } } else { while ((nread = input.Read(buffer, 0, buffer.Length)) != 0) { stream.Write(buffer, 0, nread); stream.Flush(); } } } httpHelper.OpenReadAsync(); return; } catch (Exception ex) { args = new FacebookApiEventArgs(ex, httpHelper.HttpWebRequest.IsCancelled, userState, null); } finally { input.Dispose(); } } else { input.Dispose(); var webExceptionWrapper = e.Error as WebExceptionWrapper; if (webExceptionWrapper != null) { var ex = webExceptionWrapper; if (ex.GetResponse() != null) { httpHelper.OpenReadAsync(); return; } } args = new FacebookApiEventArgs(e.Error, false, userState, null); } OnCompleted(httpMethod, args); }; httpHelper.OpenWriteAsync(); } }
public HttpWebRequestCreatedEventArgs(object userToken, HttpWebRequestWrapper httpWebRequestWrapper) { _userToken = userToken; _httpWebRequestWrapper = httpWebRequestWrapper; }