Beispiel #1
0
        private HttpWebRequest BuildWebRequest(IORequest request, IOService service, string requestUriString, string reqMethod) {

            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(requestUriString);

            webReq.Timeout = DEFAULT_RESPONSE_TIMEOUT; // in millisecods (default is 100 seconds)
            webReq.ReadWriteTimeout = DEFAULT_READWRITE_TIMEOUT; // in milliseconds

            // [MOBPLAT-200] ... Allow Gzip or Deflate decompression methods
            webReq.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
			
            if (ServiceType.MULTIPART_FORM_DATA.Equals(service.Type))
            {
                SystemLogger.Log(SystemLogger.Module.CORE, "**** [MULTIPART_FORM_DATA]. Building specific WebRequest...");
                webReq = BuildMultipartWebRequest(webReq, request, service, requestUriString);
            }
            else
            {  
                webReq.Method = reqMethod; // default is POST
                webReq.ContentType = contentTypes[service.Type];

                // check specific request ContentType defined, and override service type in that case
                if (request.ContentType != null && request.ContentType.Length > 0)
                {
                    webReq.ContentType = request.ContentType;
                }

                SystemLogger.Log(SystemLogger.Module.CORE, "Request content type: " + webReq.ContentType);
                SystemLogger.Log(SystemLogger.Module.CORE, "Request method: " + webReq.Method);

                webReq.Accept = webReq.ContentType; // setting "Accept" header with the same value as "Content Type" header, it is needed to be defined for some services.

                if (!reqMethod.Equals(RequestMethod.GET.ToString()) && request.Content != null)
                {
                    webReq.ContentLength = request.GetContentLength();
                    SystemLogger.Log(SystemLogger.Module.CORE, "Setting request ContentLength (not needed for GET): " + webReq.ContentLength);
                }

                SystemLogger.Log(SystemLogger.Module.CORE, "Request content length: " + webReq.ContentLength);
                webReq.KeepAlive = false;
            
            }

            webReq.AllowAutoRedirect = !request.StopAutoRedirect; // each request could decide if 302 redirection are automatically followed, or not. Default behaviour is to follow redirections and do not send back the 302 status code
            webReq.ProtocolVersion = HttpVersion.Version10;
            if (request.ProtocolVersion == HTTPProtocolVersion.HTTP11) webReq.ProtocolVersion = HttpVersion.Version11;

            // user agent needs to be informed - some servers check this parameter and send 500 errors when not informed.
            webReq.UserAgent = this.IOUserAgent;
            SystemLogger.Log (SystemLogger.Module.CORE, "Request UserAgent : " + webReq.UserAgent);

            /*************
             * HEADERS HANDLING
             *************/

            // add specific headers to the request
			if (request.Headers != null && request.Headers.Length > 0) {
				foreach (IOHeader header in request.Headers) {
					webReq.Headers.Add (header.Name, header.Value);
					SystemLogger.Log (SystemLogger.Module.CORE, "Added request header: " + header.Name + "=" + webReq.Headers.Get (header.Name));
				}
			}

			/*************
			 * COOKIES HANDLING
			 *************/

			// Assign the cookie container on the request to hold cookie objects that are sent on the response.
			// Required even though you no cookies are send.
			webReq.CookieContainer = this.cookieContainer;
			
			// add cookies to the request cookie container
			if (request.Session != null && request.Session.Cookies != null && request.Session.Cookies.Length > 0) {
				foreach (IOCookie cookie in request.Session.Cookies) {
					if (cookie != null && cookie.Name != null) {
						webReq.CookieContainer.Add (webReq.RequestUri, new Cookie (cookie.Name, cookie.Value));
                        SystemLogger.Log(SystemLogger.Module.CORE, "Added cookie [" + cookie.Name + "] to request. [" + cookie.Value + "]");
					}
				}
			}
			SystemLogger.Log (SystemLogger.Module.CORE, "HTTP Request cookies: " + webReq.CookieContainer.GetCookieHeader (webReq.RequestUri));
			
			/*************
			 * SETTING A PROXY (ENTERPRISE ENVIRONMENTS)
			 *************/

			if (service.Endpoint.ProxyUrl != null) {
				WebProxy myProxy = new WebProxy ();
				Uri proxyUri = new Uri (service.Endpoint.ProxyUrl);
				myProxy.Address = proxyUri;
				webReq.Proxy = myProxy;
			}

			return webReq;
		}
Beispiel #2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="request"></param>
        /// <param name="service"></param>
        /// <returns></returns>
        public virtual IOResponse InvokeService(IORequest request, IOService service)
        {
            IOResponse response = new IOResponse();

            if (service != null)
            {
                SystemLogger.Log(SystemLogger.Module.CORE, "Request content: " + request.Content);
                byte[] requestData = request.GetRawContent();

                if (service.Endpoint == null)
                {
                    SystemLogger.Log(SystemLogger.Module.CORE, "No endpoint configured for this service name: " + service.Name);
                    return(response);
                }

                string requestUriString = String.Format("{0}:{1}{2}", service.Endpoint.Host, service.Endpoint.Port, service.Endpoint.Path);
                if (service.Endpoint.Port == 0)
                {
                    requestUriString = String.Format("{0}{1}", service.Endpoint.Host, service.Endpoint.Path);
                }

                if (service.RequestMethod == RequestMethod.GET && request.Content != null)
                {
                    // add request content to the URI string when GET method.
                    requestUriString += request.Content;
                }

                SystemLogger.Log(SystemLogger.Module.CORE, "Requesting service: " + requestUriString);
                try {
                    ServicePointManager.ServerCertificateValidationCallback += delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) {
                        SystemLogger.Log(SystemLogger.Module.CORE, "*************** On ServerCertificateValidationCallback: accept all certificates");
                        return(true);
                    };

                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(requestUriString);
                    req.Method      = service.RequestMethod.ToString();                 // default is POST
                    req.ContentType = contentTypes [service.Type];

                    // check specific request ContentType defined, and override service type in that case
                    if (request.ContentType != null && request.ContentType.Length > 0)
                    {
                        req.ContentType = request.ContentType;
                    }
                    SystemLogger.Log(SystemLogger.Module.CORE, "Request content type: " + req.ContentType);
                    SystemLogger.Log(SystemLogger.Module.CORE, "Request method: " + req.Method);

                    req.Accept        = req.ContentType;              // setting "Accept" header with the same value as "Content Type" header, it is needed to be defined for some services.
                    req.ContentLength = request.GetContentLength();
                    SystemLogger.Log(SystemLogger.Module.CORE, "Request content length: " + req.ContentLength);
                    req.Timeout   = DEFAULT_RESPONSE_TIMEOUT;                   // in millisecods (default is 10 seconds)
                    req.KeepAlive = false;

                    // user agent needs to be informed - some servers check this parameter and send 500 errors when not informed.
                    req.UserAgent = this.IOUserAgent;
                    SystemLogger.Log(SystemLogger.Module.CORE, "Request UserAgent : " + req.UserAgent);

                    // add specific headers to the request
                    if (request.Headers != null && request.Headers.Length > 0)
                    {
                        foreach (IOHeader header in request.Headers)
                        {
                            req.Headers.Add(header.Name, header.Value);
                            SystemLogger.Log(SystemLogger.Module.CORE, "Added request header: " + header.Name + "=" + req.Headers.Get(header.Name));
                        }
                    }

                    // Assign the cookie container on the request to hold cookie objects that are sent on the response.
                    // Required even though you no cookies are send.
                    req.CookieContainer = this.cookieContainer;

                    // add cookies to the request cookie container
                    if (request.Session != null && request.Session.Cookies != null && request.Session.Cookies.Length > 0)
                    {
                        foreach (IOCookie cookie in request.Session.Cookies)
                        {
                            req.CookieContainer.Add(req.RequestUri, new Cookie(cookie.Name, cookie.Value));
                            SystemLogger.Log(SystemLogger.Module.CORE, "Added cookie [" + cookie.Name + "] to request.");
                        }
                    }

                    SystemLogger.Log(SystemLogger.Module.CORE, "HTTP Request cookies: " + req.CookieContainer.GetCookieHeader(req.RequestUri));

                    if (service.Endpoint.ProxyUrl != null)
                    {
                        WebProxy myProxy  = new WebProxy();
                        Uri      proxyUri = new Uri(service.Endpoint.ProxyUrl);
                        myProxy.Address = proxyUri;
                        req.Proxy       = myProxy;
                    }

                    if (req.Method == RequestMethod.POST.ToString())
                    {
                        // send data only for POST method.
                        SystemLogger.Log(SystemLogger.Module.CORE, "Sending data on the request stream... (POST)");
                        SystemLogger.Log(SystemLogger.Module.CORE, "request data length: " + requestData.Length);
                        using (Stream requestStream = req.GetRequestStream()) {
                            SystemLogger.Log(SystemLogger.Module.CORE, "request stream: " + requestStream);
                            requestStream.Write(requestData, 0, requestData.Length);
                        }
                    }

                    string result       = null;
                    byte[] resultBinary = null;

                    string responseMimeTypeOverride = null;

                    using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse()) {
                        SystemLogger.Log(SystemLogger.Module.CORE, "getting response...");
                        using (Stream stream = resp.GetResponseStream()) {
                            SystemLogger.Log(SystemLogger.Module.CORE, "getting response stream...");
                            if (ServiceType.OCTET_BINARY.Equals(service.Type))
                            {
                                // TODO workaround to avoid problems when serving binary content (corrupted content)
                                Thread.Sleep(500);

                                int lengthContent = 0;
                                if (resp.GetResponseHeader("Content-Length") != null && resp.GetResponseHeader("Content-Length") != "")
                                {
                                    lengthContent = Int32.Parse(resp.GetResponseHeader("Content-Length"));
                                }
                                if (lengthContent > 0)
                                {
                                    // Read in block
                                    resultBinary = new byte[lengthContent];
                                    stream.Read(resultBinary, 0, lengthContent);
                                }
                                else
                                {
                                    // Read to end of stream
                                    MemoryStream memBuffer  = new MemoryStream();
                                    byte[]       readBuffer = new byte[256];
                                    int          readLen    = 0;
                                    do
                                    {
                                        readLen = stream.Read(readBuffer, 0, readBuffer.Length);
                                        memBuffer.Write(readBuffer, 0, readLen);
                                    } while (readLen > 0);

                                    resultBinary = memBuffer.ToArray();
                                    memBuffer.Close();
                                    memBuffer = null;
                                }
                            }
                            else
                            {
                                SystemLogger.Log(SystemLogger.Module.CORE, "reading response content...");
                                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) {
                                    result = reader.ReadToEnd();
                                }
                            }
                        }
                        responseMimeTypeOverride = resp.GetResponseHeader("Content-Type");

                        // get response cookies (stored on cookiecontainer)
                        if (response.Session == null)
                        {
                            response.Session = new IOSessionContext();
                        }
                        response.Session.Cookies = new IOCookie[this.cookieContainer.Count];
                        IEnumerator enumerator = this.cookieContainer.GetCookies(req.RequestUri).GetEnumerator();
                        int         i          = 0;
                        while (enumerator.MoveNext())
                        {
                            Cookie cookieFound = (Cookie)enumerator.Current;
                            SystemLogger.Log(SystemLogger.Module.CORE, "Found cookie on response: " + cookieFound.Name + "=" + cookieFound.Value);
                            IOCookie cookie = new IOCookie();
                            cookie.Name  = cookieFound.Name;
                            cookie.Value = cookieFound.Value;
                            response.Session.Cookies [i] = cookie;
                            i++;
                        }
                    }

                    if (ServiceType.OCTET_BINARY.Equals(service.Type))
                    {
                        if (responseMimeTypeOverride != null && !responseMimeTypeOverride.Equals(contentTypes [service.Type]))
                        {
                            response.ContentType = responseMimeTypeOverride;
                        }
                        else
                        {
                            response.ContentType = contentTypes [service.Type];
                        }
                        response.ContentBinary = resultBinary;                         // Assign binary content here
                    }
                    else
                    {
                        response.ContentType = contentTypes [service.Type];
                        response.Content     = result;
                    }
                } catch (WebException ex) {
                    SystemLogger.Log(SystemLogger.Module.CORE, "WebException requesting service: " + requestUriString + ".", ex);
                    response.ContentType = contentTypes [ServiceType.REST_JSON];
                    response.Content     = "WebException Requesting Service: " + requestUriString + ". Message: " + ex.Message;
                } catch (Exception ex) {
                    SystemLogger.Log(SystemLogger.Module.CORE, "Unnandled Exception requesting service: " + requestUriString + ".", ex);
                    response.ContentType = contentTypes [ServiceType.REST_JSON];
                    response.Content     = "Unhandled Exception Requesting Service: " + requestUriString + ". Message: " + ex.Message;
                }
            }
            else
            {
                SystemLogger.Log(SystemLogger.Module.CORE, "Null service received for invoking.");
            }


            return(response);
        }
Beispiel #3
0
        private HttpWebRequest BuildWebRequest(IORequest request, IOService service, string requestUriString, string reqMethod)
        {
            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(requestUriString);

            webReq.Method      = reqMethod;        // default is POST
            webReq.ContentType = contentTypes [service.Type];

            // check specific request ContentType defined, and override service type in that case
            if (request.ContentType != null && request.ContentType.Length > 0)
            {
                webReq.ContentType = request.ContentType;
            }

            SystemLogger.Log(SystemLogger.Module.CORE, "Request content type: " + webReq.ContentType);
            SystemLogger.Log(SystemLogger.Module.CORE, "Request method: " + webReq.Method);

            webReq.Accept        = webReq.ContentType;      // setting "Accept" header with the same value as "Content Type" header, it is needed to be defined for some services.
            webReq.ContentLength = request.GetContentLength();
            SystemLogger.Log(SystemLogger.Module.CORE, "Request content length: " + webReq.ContentLength);
            webReq.Timeout          = DEFAULT_RESPONSE_TIMEOUT;    // in millisecods (default is 100 seconds)
            webReq.ReadWriteTimeout = DEFAULT_READWRITE_TIMEOUT;   // in milliseconds
            webReq.KeepAlive        = false;
            webReq.ProtocolVersion  = HttpVersion.Version10;
            if (request.ProtocolVersion == HTTPProtocolVersion.HTTP11)
            {
                webReq.ProtocolVersion = HttpVersion.Version11;
            }

            // [MOBPLAT-200] ... Allow Gzip or Deflate decompression methods
            webReq.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

            // user agent needs to be informed - some servers check this parameter and send 500 errors when not informed.
            webReq.UserAgent = this.IOUserAgent;
            SystemLogger.Log(SystemLogger.Module.CORE, "Request UserAgent : " + webReq.UserAgent);

            /*************
            * HEADERS HANDLING
            *************/

            // add specific headers to the request
            if (request.Headers != null && request.Headers.Length > 0)
            {
                foreach (IOHeader header in request.Headers)
                {
                    webReq.Headers.Add(header.Name, header.Value);
                    SystemLogger.Log(SystemLogger.Module.CORE, "Added request header: " + header.Name + "=" + webReq.Headers.Get(header.Name));
                }
            }

            /*************
            * COOKIES HANDLING
            *************/

            // Assign the cookie container on the request to hold cookie objects that are sent on the response.
            // Required even though you no cookies are send.
            webReq.CookieContainer = this.cookieContainer;

            // add cookies to the request cookie container
            if (request.Session != null && request.Session.Cookies != null && request.Session.Cookies.Length > 0)
            {
                foreach (IOCookie cookie in request.Session.Cookies)
                {
                    if (cookie != null && cookie.Name != null)
                    {
                        webReq.CookieContainer.Add(webReq.RequestUri, new Cookie(cookie.Name, cookie.Value));
                        SystemLogger.Log(SystemLogger.Module.CORE, "Added cookie [" + cookie.Name + "] to request.");
                    }
                }
            }
            SystemLogger.Log(SystemLogger.Module.CORE, "HTTP Request cookies: " + webReq.CookieContainer.GetCookieHeader(webReq.RequestUri));

            /*************
            * SETTING A PROXY (ENTERPRISE ENVIRONMENTS)
            *************/

            if (service.Endpoint.ProxyUrl != null)
            {
                WebProxy myProxy  = new WebProxy();
                Uri      proxyUri = new Uri(service.Endpoint.ProxyUrl);
                myProxy.Address = proxyUri;
                webReq.Proxy    = myProxy;
            }

            return(webReq);
        }
        private async Task<HttpRequestMessage> BuildWebRequest(IORequest request, IOService service, string requestUriString, string reqMethod)
        {
            var _clientBaseConfig = WindowsPhoneUtils.CreateHttpClientOptions(true);
            var requestHttpMethod = HttpMethod.Post;
            HttpRequestMessage webRequest = null;

            try
            {
                if (service.Type == ServiceType.MULTIPART_FORM_DATA)
                {
                    webRequest = await BuildMultipartWebRequest(request, service, requestUriString);
                }
                else
                {
                    switch (service.RequestMethod)
                    {
                        case RequestMethod.GET:
                            requestHttpMethod = HttpMethod.Get;
                            break;
                    }

                    if (!String.IsNullOrWhiteSpace(request.Method))
                        switch (request.Method.ToLower())
                        {
                            case "get":
                                requestHttpMethod = HttpMethod.Get;
                                break;
                            case "delete":
                                requestHttpMethod = HttpMethod.Delete;
                                break;
                            case "head":
                                requestHttpMethod = HttpMethod.Head;
                                break;
                            case "options":
                                requestHttpMethod = HttpMethod.Options;
                                break;
                            case "patch":
                                requestHttpMethod = HttpMethod.Patch;
                                break;
                            case "put":
                                requestHttpMethod = HttpMethod.Put;
                                break;
                            default:
                                requestHttpMethod = HttpMethod.Post;
                                break;

                        }

                    webRequest = new HttpRequestMessage(requestHttpMethod, new Uri(requestUriString));

                    // check specific request ContentType defined, and override service type in that case
                    // check specific request ContentType defined, and override service type in that case
                    if (requestHttpMethod == HttpMethod.Get)
                    {
                        webRequest.RequestUri =
                            new Uri(String.Concat(service.Endpoint.Host, service.Endpoint.Path, request.Content),
                                UriKind.RelativeOrAbsolute);
                    }
                    else
                    {
                        if (webRequest.Content == null && request.Content != null)
                            webRequest.Content = new HttpBufferContent(request.GetRawContent().AsBuffer());
                    }

                    var sContentType = request.ContentType;

                    if (String.IsNullOrWhiteSpace(sContentType))
                    {
                        sContentType = ContentTypes[service.Type];
                    }

                    WindowsPhoneUtils.Log("Request method: " + webRequest.Method);

                    webRequest.Headers.Accept.Add(new HttpMediaTypeWithQualityHeaderValue(sContentType));

                    if (webRequest.Method == HttpMethod.Post && request.Content != null)
                    {
                        webRequest.Content.Headers.ContentLength = (ulong?)request.GetContentLength();
                        WindowsPhoneUtils.Log("Request content length: " + request.GetContentLength());
                    }
                    else
                    {
                        webRequest.Content = new HttpStringContent("");
                    }
                    WindowsPhoneUtils.Log("webRequest content length: " + webRequest.Content.Headers.ContentLength);
                    webRequest.Content.Headers.ContentType = new HttpMediaTypeHeaderValue(sContentType);
                    webRequest.Headers.Add("Keep-Alive", "true");
                }
                if (webRequest == null) return null;
                WindowsPhoneUtils.Log("Request UserAgent : " + IOUserAgent);

                /*************
            * HEADERS HANDLING
            *************/

                // add specific headers to the request
                if (request.Headers != null && request.Headers.Length > 0)
                {
                    foreach (var header in request.Headers)
                    {
                        webRequest.Headers.Add(header.Name, header.Value);
                        WindowsPhoneUtils.Log("Added request header: " + header.Name + "=" +
                                              webRequest.Headers[header.Name]);
                    }
                }

                /*************
            * COOKIES HANDLING
            *************/

                // Assign the cookie container on the request to hold cookie objects that are sent on the response.
                // Required even though you no cookies are send.
                //webReq.CookieContainer = this.cookieContainer;

                // add cookies to the request cookie container
                if (request.Session != null && request.Session.Cookies != null && request.Session.Cookies.Length > 0)
                {
                    foreach (
                        var cookie in request.Session.Cookies.Where(cookie => !String.IsNullOrWhiteSpace(cookie.Name)))
                    {
                        _clientBaseConfig.CookieManager.SetCookie(new HttpCookie(cookie.Name, new Uri(requestUriString).Host, "/") { Value = cookie.Value });
                        WindowsPhoneUtils.Log("Added cookie [" + cookie.Name + "] to request.");
                    }
                }
                WindowsPhoneUtils.Log("HTTP Request cookies: " +
                                      _clientBaseConfig.CookieManager.GetCookies(new Uri(requestUriString)).Count);
            }
            catch (Exception ex)
            {
                WindowsPhoneUtils.Log("INVOKE SERVICE ERROR:" + ex.Message);
            }


            /*************
             * SETTING A PROXY (ENTERPRISE ENVIRONMENTS)
             *************/
            /*
            if (service.Endpoint.ProxyUrl != null)
            {
            WebProxy myProxy = new WebProxy();
            Uri proxyUri = new Uri(service.Endpoint.ProxyUrl);
            myProxy.Address = proxyUri;
            webReq.Proxy = myProxy;
            }
            */
            return webRequest;
        }
Beispiel #5
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="service"></param>
        /// <returns></returns>
        public virtual IOResponse InvokeService(IORequest request, IOService service)
        {
            IOResponse response = new IOResponse ();

            if (service != null) {
                SystemLogger.Log (SystemLogger.Module .CORE, "Request content: " + request.Content);
                byte[] requestData = request.GetRawContent ();

                if (service.Endpoint == null) {
                    SystemLogger.Log (SystemLogger.Module .CORE, "No endpoint configured for this service name: " + service.Name);
                    return response;
                }

                string requestUriString = String.Format ("{0}:{1}{2}", service.Endpoint.Host, service.Endpoint.Port, service.Endpoint.Path);
                if (service.Endpoint.Port == 0) {
                    requestUriString = String.Format ("{0}{1}", service.Endpoint.Host, service.Endpoint.Path);
                }

                if (service.RequestMethod == RequestMethod.GET && request.Content != null) {
                    // add request content to the URI string when GET method.
                    requestUriString += request.Content;
                }

                SystemLogger.Log (SystemLogger.Module .CORE, "Requesting service: " + requestUriString);
                try {

                    ServicePointManager.ServerCertificateValidationCallback += delegate(object sender,X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) {
                        SystemLogger.Log (SystemLogger.Module .CORE, "*************** On ServerCertificateValidationCallback: accept all certificates");
                        return true;
                    };

                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create (requestUriString);
                    req.Method = service.RequestMethod.ToString (); // default is POST
                    req.ContentType = contentTypes [service.Type];

                    // check specific request ContentType defined, and override service type in that case
                    if (request.ContentType != null && request.ContentType.Length > 0) {
                        req.ContentType = request.ContentType;
                    }
                    SystemLogger.Log (SystemLogger.Module.CORE, "Request content type: " + req.ContentType);
                    SystemLogger.Log (SystemLogger.Module.CORE, "Request method: " + req.Method);

                    req.Accept = req.ContentType; // setting "Accept" header with the same value as "Content Type" header, it is needed to be defined for some services.
                    req.ContentLength = request.GetContentLength ();
                    SystemLogger.Log (SystemLogger.Module.CORE, "Request content length: " + req.ContentLength);
                    req.Timeout = DEFAULT_RESPONSE_TIMEOUT; // in millisecods (default is 10 seconds)
                    req.KeepAlive = false;

                    // user agent needs to be informed - some servers check this parameter and send 500 errors when not informed.
                    req.UserAgent = this.IOUserAgent;
                    SystemLogger.Log (SystemLogger.Module.CORE, "Request UserAgent : " + req.UserAgent);

                    // add specific headers to the request
                    if (request.Headers != null && request.Headers.Length > 0) {
                        foreach (IOHeader header in request.Headers) {
                            req.Headers.Add (header.Name, header.Value);
                            SystemLogger.Log (SystemLogger.Module.CORE, "Added request header: " + header.Name + "=" + req.Headers.Get (header.Name));
                        }
                    }

                    // Assign the cookie container on the request to hold cookie objects that are sent on the response.
                    // Required even though you no cookies are send.
                    req.CookieContainer = this.cookieContainer;

                    // add cookies to the request cookie container
                    if (request.Session != null && request.Session.Cookies != null && request.Session.Cookies.Length > 0) {
                        foreach (IOCookie cookie in request.Session.Cookies) {
                            req.CookieContainer.Add (req.RequestUri, new Cookie (cookie.Name, cookie.Value));
                            SystemLogger.Log (SystemLogger.Module.CORE, "Added cookie [" + cookie.Name + "] to request.");
                        }
                    }

                    SystemLogger.Log (SystemLogger.Module.CORE, "HTTP Request cookies: " + req.CookieContainer.GetCookieHeader (req.RequestUri));

                    if (service.Endpoint.ProxyUrl != null) {
                        WebProxy myProxy = new WebProxy ();
                        Uri proxyUri = new Uri (service.Endpoint.ProxyUrl);
                        myProxy.Address = proxyUri;
                        req.Proxy = myProxy;
                    }

                    if (req.Method == RequestMethod.POST.ToString ()) {
                        // send data only for POST method.
                        SystemLogger.Log (SystemLogger.Module.CORE, "Sending data on the request stream... (POST)");
                        SystemLogger.Log (SystemLogger.Module.CORE, "request data length: " + requestData.Length);
                        using (Stream requestStream = req.GetRequestStream()) {
                            SystemLogger.Log (SystemLogger.Module.CORE, "request stream: " + requestStream);
                            requestStream.Write (requestData, 0, requestData.Length);
                        }
                    }

                    string result = null;
                    byte[] resultBinary = null;

                    string responseMimeTypeOverride = null;

                    using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse()) {
                        SystemLogger.Log (SystemLogger.Module.CORE, "getting response...");
                        using (Stream stream = resp.GetResponseStream()) {
                            SystemLogger.Log (SystemLogger.Module.CORE, "getting response stream...");
                            if (ServiceType.OCTET_BINARY.Equals (service.Type)) {

                                // TODO workaround to avoid problems when serving binary content (corrupted content)
                                Thread.Sleep (500);

                                int lengthContent = 0;
                                if (resp.GetResponseHeader ("Content-Length") != null && resp.GetResponseHeader ("Content-Length") != "") {
                                    lengthContent = Int32.Parse (resp.GetResponseHeader ("Content-Length"));
                                }
                                if (lengthContent > 0) {
                                    // Read in block
                                    resultBinary = new byte[lengthContent];
                                    stream.Read (resultBinary, 0, lengthContent);
                                } else {
                                    // Read to end of stream
                                    MemoryStream memBuffer = new MemoryStream ();
                                    byte[] readBuffer = new byte[256];
                                    int readLen = 0;
                                    do {
                                        readLen = stream.Read (readBuffer, 0, readBuffer.Length);
                                        memBuffer.Write (readBuffer, 0, readLen);
                                    } while (readLen >0);

                                    resultBinary = memBuffer.ToArray ();
                                    memBuffer.Close ();
                                    memBuffer = null;
                                }
                            } else {
                                SystemLogger.Log (SystemLogger.Module.CORE, "reading response content...");
                                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) {
                                    result = reader.ReadToEnd ();
                                }
                            }
                        }
                        responseMimeTypeOverride = resp.GetResponseHeader ("Content-Type");

                        // get response cookies (stored on cookiecontainer)
                        if (response.Session == null) {
                            response.Session = new IOSessionContext ();

                        }
                        response.Session.Cookies = new IOCookie[this.cookieContainer.Count];
                        IEnumerator enumerator = this.cookieContainer.GetCookies (req.RequestUri).GetEnumerator ();
                        int i = 0;
                        while (enumerator.MoveNext()) {
                            Cookie cookieFound = (Cookie)enumerator.Current;
                            SystemLogger.Log (SystemLogger.Module.CORE, "Found cookie on response: " + cookieFound.Name + "=" + cookieFound.Value);
                            IOCookie cookie = new IOCookie ();
                            cookie.Name = cookieFound.Name;
                            cookie.Value = cookieFound.Value;
                            response.Session.Cookies [i] = cookie;
                            i++;
                        }
                    }

                    if (ServiceType.OCTET_BINARY.Equals (service.Type)) {
                        if (responseMimeTypeOverride != null && !responseMimeTypeOverride.Equals (contentTypes [service.Type])) {
                            response.ContentType = responseMimeTypeOverride;
                        } else {
                            response.ContentType = contentTypes [service.Type];
                        }
                        response.ContentBinary = resultBinary; // Assign binary content here
                    } else {
                        response.ContentType = contentTypes [service.Type];
                        response.Content = result;
                    }

                } catch (WebException ex) {
                    SystemLogger.Log (SystemLogger.Module .CORE, "WebException requesting service: " + requestUriString + ".", ex);
                    response.ContentType = contentTypes [ServiceType.REST_JSON];
                    response.Content = "WebException Requesting Service: " + requestUriString + ". Message: " + ex.Message;
                } catch (Exception ex) {
                    SystemLogger.Log (SystemLogger.Module .CORE, "Unnandled Exception requesting service: " + requestUriString + ".", ex);
                    response.ContentType = contentTypes [ServiceType.REST_JSON];
                    response.Content = "Unhandled Exception Requesting Service: " + requestUriString + ". Message: " + ex.Message;
                }
            } else {
                SystemLogger.Log (SystemLogger.Module .CORE, "Null service received for invoking.");
            }

            return response;
        }
Beispiel #6
0
        private HttpWebRequest BuildWebRequest(IORequest request, IOService service, string requestUriString, string reqMethod)
        {
            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create (requestUriString);
            webReq.Method = reqMethod; // default is POST
            webReq.ContentType = contentTypes [service.Type];

                    // check specific request ContentType defined, and override service type in that case
                    if (request.ContentType != null && request.ContentType.Length > 0) {
                webReq.ContentType = request.ContentType;
                    }

            SystemLogger.Log (SystemLogger.Module.CORE, "Request content type: " + webReq.ContentType);
            SystemLogger.Log (SystemLogger.Module.CORE, "Request method: " + webReq.Method);

            webReq.Accept = webReq.ContentType; // setting "Accept" header with the same value as "Content Type" header, it is needed to be defined for some services.
            webReq.ContentLength = request.GetContentLength ();
            SystemLogger.Log (SystemLogger.Module.CORE, "Request content length: " + webReq.ContentLength);
            webReq.Timeout = DEFAULT_RESPONSE_TIMEOUT; // in millisecods (default is 100 seconds)
            webReq.ReadWriteTimeout = DEFAULT_READWRITE_TIMEOUT; // in milliseconds
            webReq.KeepAlive = false;
            webReq.ProtocolVersion = HttpVersion.Version10;
            if (request.ProtocolVersion == HTTPProtocolVersion.HTTP11) webReq.ProtocolVersion = HttpVersion.Version11;

                    // user agent needs to be informed - some servers check this parameter and send 500 errors when not informed.
            webReq.UserAgent = this.IOUserAgent;
            SystemLogger.Log (SystemLogger.Module.CORE, "Request UserAgent : " + webReq.UserAgent);

            /*************
             * HEADERS HANDLING
             *************/

                    // add specific headers to the request
                    if (request.Headers != null && request.Headers.Length > 0) {
                        foreach (IOHeader header in request.Headers) {
                    webReq.Headers.Add (header.Name, header.Value);
                    SystemLogger.Log (SystemLogger.Module.CORE, "Added request header: " + header.Name + "=" + webReq.Headers.Get (header.Name));
                        }
                    }

            /*************
             * COOKIES HANDLING
             *************/

                    // Assign the cookie container on the request to hold cookie objects that are sent on the response.
                    // Required even though you no cookies are send.
            webReq.CookieContainer = this.cookieContainer;

                    // add cookies to the request cookie container
                    if (request.Session != null && request.Session.Cookies != null && request.Session.Cookies.Length > 0) {
                        foreach (IOCookie cookie in request.Session.Cookies) {
                    webReq.CookieContainer.Add (webReq.RequestUri, new Cookie (cookie.Name, cookie.Value));
                            SystemLogger.Log (SystemLogger.Module.CORE, "Added cookie [" + cookie.Name + "] to request.");
                        }
                    }
            SystemLogger.Log (SystemLogger.Module.CORE, "HTTP Request cookies: " + webReq.CookieContainer.GetCookieHeader (webReq.RequestUri));

            /*************
             * SETTING A PROXY (ENTERPRISE ENVIRONMENTS)
             *************/

                    if (service.Endpoint.ProxyUrl != null) {
                        WebProxy myProxy = new WebProxy ();
                        Uri proxyUri = new Uri (service.Endpoint.ProxyUrl);
                        myProxy.Address = proxyUri;
                webReq.Proxy = myProxy;
                    }

            return webReq;
        }