public void Echo()
        {
            IClientHttpRequest request = this.CreateRequest("/echo", HttpMethod.PUT);

            request.Headers.ContentType = new MediaType("text", "plain", "utf-8");
            String headerName   = "MyHeader";
            String headerValue1 = "value1";

            request.Headers.Add(headerName, headerValue1);
            String headerValue2 = "value2";

            request.Headers.Add(headerName, headerValue2);

            byte[] body = Encoding.UTF8.GetBytes("Hello World");
            request.Body = delegate(Stream stream)
            {
                stream.Write(body, 0, body.Length);
            };

            using (IClientHttpResponse response = request.Execute())
            {
                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "Invalid status code");
                Assert.AreEqual("value1,value2", response.Headers[headerName], "Header values not found");
                using (BinaryReader reader = new BinaryReader(response.Body))
                {
                    byte[] result = reader.ReadBytes((int)response.Headers.ContentLength);
                    Assert.AreEqual(body, result, "Invalid body");
                }
            }
        }
        public void SetUp()
        {
            mocks = new MockRepository();
            response = mocks.StrictMock<IClientHttpResponse>();

            responseErrorHandler = new DefaultResponseErrorHandler();
        }
        public void SetUp()
        {
            mocks    = new MockRepository();
            response = mocks.StrictMock <IClientHttpResponse>();

            responseErrorHandler = new DefaultResponseErrorHandler();
        }
        public override void HandleError(Uri requestUri, HttpMethod requestMethod, IClientHttpResponse response)
        {
            var statusCode = response.StatusCode;

            switch (statusCode)
            {
                case HttpStatusCode.BadRequest:
                    throw new oDeskApiException("Missing parameter.");
                    break;

                case HttpStatusCode.Forbidden:
                    throw new oDeskApiException("Could not authenticate with OAuth.");
                    break;

                case HttpStatusCode.InternalServerError:
                    throw new oDeskApiException("oDesk server error.");
                    break;

                case HttpStatusCode.RequestTimeout:
                    throw new oDeskApiException("oDesk did not respond in a timely manner.");
                    break;

                case HttpStatusCode.ServiceUnavailable:
                    throw new oDeskApiException("oDesk is unavailable.");
                    break;

                case HttpStatusCode.Unauthorized:
                    throw new oDeskApiException("Could not authenticate with OAuth.");
                    break;

                default:
                    base.HandleError(requestUri, requestMethod, response);
                    break;
            }
        }
            // IClientHttpRequestSyncInterceptor
            public IClientHttpResponse Execute(IClientHttpRequestSyncExecution execution)
            {
                execution.Headers.Add("BeforeSyncExecution", "MyValue");
                IClientHttpResponse response = execution.Execute();

                response.Headers.Add("AfterSyncExecution", "MyValue");
                return(response);
            }
            public IClientHttpResponse Execute(IClientHttpRequestSyncExecution execution)
            {
                HandleRequestCounter = ++counter;
                IClientHttpResponse response = execution.Execute();

                HandleResponseCounter = ++counter;
                return(response);
            }
 /// <summary>
 /// Indicates whether or not the given response has a message body.
 /// </summary>
 /// <remarks>
 /// Default implementation returns false for a response status of 204 or 304, or a 'Content-Length' of 0.
 /// </remarks>
 /// <param name="response">The response to check for a message body.</param>
 /// <returns><see langword="true"/> if the response has a body; otherwise <see langword="false"/>.</returns>
 protected virtual bool HasMessageBody(IClientHttpResponse response)
 {
     if (response.StatusCode == HttpStatusCode.NoContent ||
         response.StatusCode == HttpStatusCode.NotModified)
     {
         return(false);
     }
     return(response.Headers.ContentLength != 0);
 }
        // This is the method that the underlying, free-threaded asynchronous behavior will invoke.
        // This will happen on an arbitrary thread.
        private void ExecuteAsyncCallback(ExecuteState state, IClientHttpResponse response, Exception exception)
        {
            // Package the results of the operation
            ClientHttpRequestCompletedEventArgs eventArgs = new ClientHttpRequestCompletedEventArgs(response, exception, this.isCancelled, state.AsyncOperation.UserSuppliedState);
            ExecuteCallbackArgs <ClientHttpRequestCompletedEventArgs> callbackArgs = new ExecuteCallbackArgs <ClientHttpRequestCompletedEventArgs>(eventArgs, state.ExecuteCompleted);

            // End the task. The asyncOp object is responsible for marshaling the call.
            state.AsyncOperation.PostOperationCompleted(ExecuteResponseReceived, callbackArgs);
        }
 /// <summary>
 /// Handles the error in the given response. 
 /// This method is only called when <see cref="M:HasError"/> has returned <see langword="true"/>.
 /// </summary>
 /// <param name="response">The response with the error</param>
 public virtual void HandleError(IClientHttpResponse response)
 {
     byte[] body = null;
     using (MemoryStream tempStream = new MemoryStream())
     {
         IoUtils.CopyStream(response.Body, tempStream);
         body = tempStream.ToArray();
     }
     this.HandleError(new HttpResponseMessage<byte[]>(body, response.Headers, response.StatusCode, response.StatusDescription));
 }
Beispiel #10
0
        public void NtlmAuthorizationKO()
        {
            IClientHttpRequest request = this.CreateRequest("/ntlm/echo", HttpMethod.PUT);

            request.Headers.ContentLength = 0;
            using (IClientHttpResponse response = request.Execute())
            {
                Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode, "Invalid status code");
            }
        }
        public void Status()
        {
            IClientHttpRequest request = this.CreateRequest("/status/notfound", HttpMethod.GET);

            using (IClientHttpResponse response = request.Execute())
            {
                Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode, "Invalid status code");
                Assert.AreEqual("Status NotFound", response.StatusDescription, "Invalid status description");
            }
        }
        public void BasicAuthorizationOK()
        {
            IClientHttpRequest request = this.CreateRequest(
                new BasicSigningRequestInterceptor("login", "password"), "/basic/echo", HttpMethod.PUT);

            request.Headers.ContentLength = 0;
            using (IClientHttpResponse response = request.Execute())
            {
                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "Invalid status code");
            }
        }
        public void ChangeResponse()
        {
            ChangeResponseInterceptor interceptor = new ChangeResponseInterceptor();

            requestFactory = new InterceptingClientHttpRequestFactory(requestFactoryMock,
                                                                      new IClientHttpRequestInterceptor[] { interceptor });

            IClientHttpRequest  request  = requestFactory.CreateRequest(new Uri("http://example.com"), HttpMethod.GET);
            IClientHttpResponse response = request.Execute();

            Assert.AreNotSame(this.responseMock, response);
        }
Beispiel #14
0
        public void NtlmAuthorizationOK()
        {
            this.webRequestFactory.UseDefaultCredentials = true;

            IClientHttpRequest request = this.CreateRequest("/ntlm/echo", HttpMethod.PUT);

            request.Headers.ContentLength = 0;
            using (IClientHttpResponse response = request.Execute())
            {
                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "Invalid status code");
            }
        }
            public ResponseAsyncContext(ClientHttpRequestCompletedEventArgs completedEventArgs)
            {
                this.cancelled = completedEventArgs.Cancelled;
                this.error     = completedEventArgs.Error;
                if (this.error == null)
                {
                    this.response = completedEventArgs.Response;
                }
                this.userState = completedEventArgs.UserState;

                this.completedEventArgs = completedEventArgs;
            }
        private void AssertHttpMethod(String path, HttpMethod method)
        {
            IClientHttpRequest request = this.CreateRequest("/methods/" + path, method);

            request.Headers.ContentLength = 0;

            using (IClientHttpResponse response = request.Execute())
            {
                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "Invalid status code");
                Assert.AreEqual(path, response.StatusDescription, "Invalid status description");
            }
        }
Beispiel #17
0
        public void BasicAuthorizationKO()
        {
            this.webRequestFactory.Credentials = new NetworkCredential("bruno", "password");

            IClientHttpRequest request = this.CreateRequest("/basic/echo", HttpMethod.PUT);

            request.Headers.ContentLength = 0;
            using (IClientHttpResponse response = request.Execute())
            {
                Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode, "Invalid status code");
            }
        }
Beispiel #18
0
        public void RangeHeader()
        {
            IClientHttpRequest request = this.CreateRequest("/echo", HttpMethod.PUT);

            request.Headers.ContentLength = 0;
            request.Headers["Range"]      = "bytes=128-1024";

            using (IClientHttpResponse response = request.Execute())
            {
                Assert.AreEqual("bytes=128-1024", response.Headers["Range"]);
                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "OK");
            }
        }
 public virtual void HandleError(Uri requestUri, HttpMethod requestMethod, IClientHttpResponse response)
 {
     byte[] body = null;
     Stream source = response.Body;
     if (source != null)
     {
         using (MemoryStream stream2 = new MemoryStream())
         {
             IoUtils.CopyStream(source, stream2);
             body = stream2.ToArray();
         }
     }
     this.HandleError(requestUri, requestMethod, new HttpResponseMessage<byte[]>(body, response.Headers, response.StatusCode, response.StatusDescription));
 }
        public void NoSyncExecution()
        {
            NoOpExecutionInterceptor   interceptor1 = new NoOpExecutionInterceptor();
            NoOpRequestSyncInterceptor interceptor2 = new NoOpRequestSyncInterceptor();

            requestFactory = new InterceptingClientHttpRequestFactory(requestFactoryMock,
                                                                      new IClientHttpRequestInterceptor[] { interceptor1, interceptor2 });

            IClientHttpRequest  request  = requestFactory.CreateRequest(new Uri("http://example.com"), HttpMethod.GET);
            IClientHttpResponse response = request.Execute();

            Assert.IsFalse(interceptor2.invoked);
            Assert.IsFalse(requestMock.executed);
        }
        /// <summary>
        /// Handles the error in the given response.
        /// <para/>
        /// This method is only called when HasError() method has returned <see langword="true"/>.
        /// </summary>
        /// <param name="requestUri">The request URI.</param>
        /// <param name="requestMethod">The request method.</param>
        /// <param name="response">The response with the error</param>
        public virtual void HandleError(Uri requestUri, HttpMethod requestMethod, IClientHttpResponse response)
        {
            byte[] body       = null;
            Stream bodyStream = response.Body;

            if (bodyStream != null)
            {
                using (MemoryStream tempStream = new MemoryStream())
                {
                    IoUtils.CopyStream(bodyStream, tempStream);
                    body = tempStream.ToArray();
                }
            }
            this.HandleError(requestUri, requestMethod, new HttpResponseMessage <byte[]>(body, response.Headers, response.StatusCode, response.StatusDescription));
        }
        /// <summary>
        /// Execute this request asynchronously.
        /// </summary>
        /// <param name="state">
        /// An optional user-defined object that is passed to the method invoked
        /// when the asynchronous operation completes.
        /// </param>
        /// <param name="executeCompleted">
        /// The <see cref="Action{ClientHttpRequestCompletedEventArgs}"/> to perform when the asynchronous execution completes.
        /// </param>
        public void ExecuteAsync(object state, Action <ClientHttpRequestCompletedEventArgs> executeCompleted)
        {
            foreach (RequestMatcher requestMatcher in this.requestMatchers)
            {
                requestMatcher(this);
            }

            IClientHttpResponse response = null;

            if (this.responseCreator != null)
            {
                response = responseCreator(this);
            }
            executeCompleted(new ClientHttpRequestCompletedEventArgs(response, null, false, state));
        }
	    public void SetUp() 
        {
            mocks = new MockRepository();
            requestFactory = mocks.StrictMock<IClientHttpRequestFactory>();
            request = mocks.StrictMock<IClientHttpRequest>();
            response = mocks.StrictMock<IClientHttpResponse>();
            errorHandler = mocks.StrictMock<IResponseErrorHandler>();
            converter = mocks.StrictMock<IHttpMessageConverter>();
            
            IList<IHttpMessageConverter> messageConverters = new List<IHttpMessageConverter>(1);
            messageConverters.Add(converter);

            template = new RestTemplate();
            template.RequestFactory = requestFactory;
            template.MessageConverters = messageConverters;
            template.ErrorHandler = errorHandler;
	    }
Beispiel #24
0
        public void SetUp()
        {
            mocks          = new MockRepository();
            requestFactory = mocks.StrictMock <IClientHttpRequestFactory>();
            request        = mocks.StrictMock <IClientHttpRequest>();
            response       = mocks.StrictMock <IClientHttpResponse>();
            errorHandler   = mocks.StrictMock <IResponseErrorHandler>();
            converter      = mocks.StrictMock <IHttpMessageConverter>();

            IList <IHttpMessageConverter> messageConverters = new List <IHttpMessageConverter>(1);

            messageConverters.Add(converter);

            template = new RestTemplate();
            template.RequestFactory    = requestFactory;
            template.MessageConverters = messageConverters;
            template.ErrorHandler      = errorHandler;
        }
        /// <summary>
        /// Gets called by <see cref="RestTemplate"/> with an opened <see cref="IClientHttpResponse"/> to extract data.
        /// Does not need to care about closing the request or about handling errors:
        /// this will all be handled by the <see cref="RestTemplate"/> class.
        /// </summary>
        /// <param name="response">The active HTTP request.</param>
        public virtual T ExtractData(IClientHttpResponse response)
        {
            if (!this.HasMessageBody(response))
            {
                return(null);
            }
            MediaType mediaType = response.Headers.ContentType;

            if (mediaType == null)
            {
                #region Instrumentation
#if !SILVERLIGHT && !CF_3_5
                if (LOG.IsWarnEnabled)
                {
                    LOG.Warn("No Content-Type header found, defaulting to 'application/octet-stream'");
                }
#endif
                #endregion

                mediaType = MediaType.APPLICATION_OCTET_STREAM;
            }
            foreach (IHttpMessageConverter messageConverter in messageConverters)
            {
                if (messageConverter.CanRead(typeof(T), mediaType))
                {
                    #region Instrumentation
#if !SILVERLIGHT && !CF_3_5
                    if (LOG.IsDebugEnabled)
                    {
                        LOG.Debug(String.Format(
                                      "Reading [{0}] as '{1}' using [{2}]",
                                      typeof(T).FullName, mediaType, messageConverter));
                    }
#endif
                    #endregion

                    return(messageConverter.Read <T>(response));
                }
            }
            throw new RestClientException(String.Format(
                                              "Could not extract response: no suitable HttpMessageConverter found for response type [{0}] and content type [{1}]",
                                              typeof(T).FullName, mediaType));
        }
Beispiel #26
0
        public void SpecialHeaders() // related to HttpWebRequest implementation
        {
            IClientHttpRequest request = this.CreateRequest("/echo", HttpMethod.PUT);

            request.Headers.Accept        = new MediaType[] { MediaType.ALL };
            request.Headers.ContentType   = MediaType.TEXT_PLAIN;
            request.Headers["Connection"] = "close";
            request.Headers.ContentLength = 0;
#if NET_4_0
            request.Headers.Date = DateTime.Now;
#endif
            request.Headers["Expect"]       = "bla";
            request.Headers.IfModifiedSince = DateTime.Now;
            request.Headers["Referer"]      = "http://www.springframework.net/";
            //request.Headers["Transfer-Encoding"] = "Identity";
            request.Headers["User-Agent"] = "Unit tests";

            using (IClientHttpResponse response = request.Execute())
            {
                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "Invalid status code");
            }
        }
        public void BeforeExecution()
        {
            NoOpRequestBeforeInterceptor interceptor1 = new NoOpRequestBeforeInterceptor();
            NoOpRequestBeforeInterceptor interceptor2 = new NoOpRequestBeforeInterceptor();

            requestFactory = new InterceptingClientHttpRequestFactory(requestFactoryMock,
                                                                      new IClientHttpRequestInterceptor[] { interceptor1, interceptor2 });

            IClientHttpRequest request = requestFactory.CreateRequest(new Uri("http://example.com"), HttpMethod.GET);

            Assert.IsFalse(interceptor1.invoked);
            Assert.IsFalse(interceptor2.invoked);
            Assert.IsTrue(this.requestFactoryMock.created);
            Assert.IsFalse(this.requestMock.executed);

            IClientHttpResponse response = request.Execute();

            Assert.IsTrue(interceptor1.invoked);
            Assert.IsTrue(interceptor2.invoked);
            Assert.IsTrue(this.requestMock.executed);
            Assert.AreSame(this.responseMock, response);
        }
        private void ExecuteResponseCallback(IAsyncResult result)
        {
            ExecuteState state = (ExecuteState)result.AsyncState;

            IClientHttpResponse response  = null;
            Exception           exception = null;

            try
            {
                HttpWebResponse httpWebResponse = this.httpWebRequest.EndGetResponse(result) as HttpWebResponse;
                if (this.httpWebRequest.HaveResponse == true && httpWebResponse != null)
                {
                    response = this.CreateClientHttpResponse(httpWebResponse);
                }
            }
            catch (Exception ex)
            {
                if (ex is ThreadAbortException || ex is StackOverflowException || ex is OutOfMemoryException)
                {
                    throw;
                }
                exception = ex;
                // This exception can be raised with some status code
                // Try to retrieve the response from the error
                if (ex is WebException)
                {
                    HttpWebResponse httpWebResponse = ((WebException)ex).Response as HttpWebResponse;
                    if (httpWebResponse != null)
                    {
                        exception = null;
                        response  = this.CreateClientHttpResponse(httpWebResponse);
                    }
                }
            }

            ExecuteAsyncCallback(state, response, exception);
        }
Beispiel #29
0
 /// <summary>
 /// Gets called by <see cref="RestTemplate"/> with an opened <see cref="IClientHttpResponse"/> to extract data.
 /// Does not need to care about closing the request or about handling errors:
 /// this will all be handled by the <see cref="RestTemplate"/> class.
 /// </summary>
 /// <param name="response">The active HTTP request.</param>
 public HttpHeaders ExtractData(IClientHttpResponse response)
 {
     return(response.Headers);
 }
Beispiel #30
0
 /// <summary>
 /// Creates a new instance of <see cref="ClientHttpRequestCompletedEventArgs"/>.
 /// </summary>
 /// <param name="response">The response of the execution.</param>
 /// <param name="exception">Any error that occurred during the asynchronous execution.</param>
 /// <param name="cancelled">A value indicating whether the asynchronous execution was canceled.</param>
 /// <param name="userState">The optional user-supplied state object.</param>
 public ClientHttpRequestCompletedEventArgs(IClientHttpResponse response, Exception exception, bool cancelled, object userState)
     : base(exception, cancelled, userState)
 {
     this.response = response;
 }
 public ResponseAsyncContext(ClientHttpRequestCompletedEventArgs completedEventArgs)
 {
     this.cancelled = completedEventArgs.Cancelled;
     this.error = completedEventArgs.Error;
     if (this.error == null)
     {
         this.response = completedEventArgs.Response;
     }
     this.userState = completedEventArgs.UserState;
     this.completedEventArgs = completedEventArgs;
 }
Beispiel #32
0
 /// <summary>
 /// Gets called by <see cref="RestTemplate"/> with an opened <see cref="IClientHttpResponse"/> to extract data.
 /// Does not need to care about closing the request or about handling errors:
 /// this will all be handled by the <see cref="RestTemplate"/> class.
 /// </summary>
 /// <param name="response">The active HTTP request.</param>
 public HttpResponseMessage ExtractData(IClientHttpResponse response)
 {
     return(new HttpResponseMessage(response.Headers, response.StatusCode, response.StatusDescription));
 }
 public virtual bool HasError(Uri requestUri, HttpMethod requestMethod, IClientHttpResponse response)
 {
     return this.HasError(response.StatusCode);
 }
 /// <summary>
 /// Indicates whether the given response has any errors.
 /// <para/>
 /// This implementation delegates to HasError(HttpStatusCode) method with the response status code.
 /// </summary>
 /// <param name="requestUri">The request URI.</param>
 /// <param name="requestMethod">The request method.</param>
 /// <param name="response">The response to inspect.</param>
 /// <returns>
 /// <see langword="true"/> if the response has an error; otherwise <see langword="false"/>.
 /// </returns>
 public virtual bool HasError(Uri requestUri, HttpMethod requestMethod, IClientHttpResponse response)
 {
     return(this.HasError(response.StatusCode));
 }
 /// <summary>
 /// Indicates whether the given response has any errors.
 /// </summary>
 /// <remarks>
 /// This implementation delegates to <see cref="M:HasError(HttpStatusCode)"/> 
 /// with the response status code.
 /// </remarks>
 /// <param name="response">The response to inspect.</param>
 /// <returns>
 /// <see langword="true"/> if the response has an error; otherwise <see langword="false"/>.
 /// </returns>
 public virtual bool HasError(IClientHttpResponse response)
 {
     return this.HasError(response.StatusCode);
 }
        /// <summary>
        /// Gets called by <see cref="RestTemplate"/> with an opened <see cref="IClientHttpResponse"/> to extract data.
        /// Does not need to care about closing the request or about handling errors:
        /// this will all be handled by the <see cref="RestTemplate"/> class.
        /// </summary>
        /// <param name="response">The active HTTP request.</param>
        public HttpResponseMessage <T> ExtractData(IClientHttpResponse response)
        {
            T body = httpMessageConverterExtractor.ExtractData(response);

            return(new HttpResponseMessage <T>(body, response.Headers, response.StatusCode, response.StatusDescription));
        }
Beispiel #37
0
 /// <summary>
 /// Gets called by <see cref="RestTemplate"/> with an opened <see cref="IClientHttpResponse"/> to extract data.
 /// Does not need to care about closing the request or about handling errors:
 /// this will all be handled by the <see cref="RestTemplate"/> class.
 /// </summary>
 /// <param name="response">The active HTTP request.</param>
 public Uri ExtractData(IClientHttpResponse response)
 {
     return(response.Headers.Location);
 }
 /// <summary>
 /// Gets called by <see cref="RestTemplate"/> with an opened <see cref="IClientHttpResponse"/> to extract data.
 /// Does not need to care about closing the request or about handling errors:
 /// this will all be handled by the <see cref="RestTemplate"/> class.
 /// </summary>
 /// <param name="response">The active HTTP request.</param>
 public IList <HttpMethod> ExtractData(IClientHttpResponse response)
 {
     return(new List <HttpMethod>(response.Headers.Allow));
 }
 public ClientHttpRequestCompletedEventArgs(IClientHttpResponse response, Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState)
 {
     this.response = response;
 }