Ejemplo n.º 1
0
        public static string Post(string url, string PostString, SecurityProtocolType?securityProtocolType = null)
        {
            HttpWebRequest request = null;

            try
            {
                if (securityProtocolType != null)
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    ServicePointManager.SecurityProtocol = (SecurityProtocolType)securityProtocolType;
                }

                request             = (HttpWebRequest)HttpWebRequest.Create(url);
                request.Method      = "POST";
                request.ContentType = "application/x-www-form-urlencoded";

                byte[]           postData  = Encoding.UTF8.GetBytes(PostString);
                System.IO.Stream reqStream = request.GetRequestStream();
                reqStream.Write(postData, 0, postData.Length);
                reqStream.Close();

                using (WebResponse wr = request.GetResponse())
                {
                    Stream       st = wr.GetResponseStream();
                    StreamReader sr = new StreamReader(st);
                    return(sr.ReadToEnd());
                }
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }
Ejemplo n.º 2
0
        public static HttpRequestResult ExecuteJsonWebRequest <T>(out string response, out Dictionary <string, string> responseHeaders, string url, T postContent, bool disableCertificateValidation, Dictionary <string, string> customHeaders, TimeSpan?timeout = null, string requestMethod = "POST", SecurityProtocolType?securityProtocolType = null)
        {
            var postData = postContent.ToJson();

            var existingContentTypeKey =
                customHeaders.Keys.FirstOrDefault(
                    k => k.Equals("content-type", StringComparison.CurrentCultureIgnoreCase));

            if (existingContentTypeKey != null && !existingContentTypeKey.IsNullOrEmpty())
            {
                customHeaders[existingContentTypeKey] = "application/json";
            }
            else
            {
                customHeaders.Add("content-type", "application/json");
            }

            return(ExecuteWebRequest(out response, out responseHeaders, url, postData, disableCertificateValidation, customHeaders, null, requestMethod, timeout, securityProtocolType: securityProtocolType));
        }
Ejemplo n.º 3
0
        public static HttpRequestResult ExecuteJsonWebRequest <T>(out string response, string url, T postContent,
                                                                  bool disableCertificateValidation, Dictionary <string, string> customHeaders, TimeSpan?timeout = null, SecurityProtocolType?securityProtocolType = null)
        {
            Dictionary <string, string> responseHeaders;

            return(ExecuteJsonWebRequest(out response, out responseHeaders, url, postContent, disableCertificateValidation,
                                         customHeaders, timeout, securityProtocolType: securityProtocolType));
        }
Ejemplo n.º 4
0
 public static HttpRequestResult ExecutePutRequest(out string response, out Dictionary <string, string> responseHeaders, string url, string postContent, bool disableCertificateValidation, Dictionary <string, string> customHeaders, TimeSpan?timeout = null, string requestMethod = "POST", SecurityProtocolType?securityProtocolType = null)
 {
     return(ExecuteWebRequest(out response, out responseHeaders, url, postContent, disableCertificateValidation, customHeaders, null, "PUT", timeout, securityProtocolType: securityProtocolType));
 }
Ejemplo n.º 5
0
 public static HttpRequestResult ExecutePostRequest(out string response, out Dictionary <string, string> responseHeaders, string url, string postContent, TimeSpan?timeout = null, SecurityProtocolType?securityProtocolType = null)
 {
     return(ExecutePostRequest(out response, out responseHeaders, url, postContent, true, new Dictionary <string, string>(), timeout, securityProtocolType));
 }
Ejemplo n.º 6
0
 public static HttpRequestResult ExecuteGetRequest(out string response, out Dictionary <string, string> responseHeaders, string url, bool disableCertificateValidation, Dictionary <string, string> customHeaders, HttpCookieCollection cookies, TimeSpan?timeout = null, SecurityProtocolType?securityProtocolType = null)
 {
     return(ExecuteWebRequest(out response, out responseHeaders, url, "", disableCertificateValidation,
                              customHeaders, cookies, "GET", timeout, securityProtocolType: securityProtocolType));
 }
Ejemplo n.º 7
0
 public static HttpRequestResult ExecuteGetRequest(out string response, string url, TimeSpan?timeout = null, SecurityProtocolType?securityProtocolType = null)
 {
     return(ExecuteGetRequest(out response, url, true, new Dictionary <string, string>(), timeout, securityProtocolType));
 }
Ejemplo n.º 8
0
        public static HttpRequestResult ExecuteWebRequest(out string response, out Dictionary <string, string> responseHeaders, string url, string postContent, bool disableCertificateValidation, Dictionary <string, string> customHeaders, HttpCookieCollection cookies, string requestMethod = "POST", TimeSpan?timeout = null, X509Certificate2 certificate = null, SecurityProtocolType?securityProtocolType = null)
        {
            responseHeaders = new Dictionary <string, string>();

            var encoding = new UTF8Encoding();
            var data     = encoding.GetBytes(postContent);

            if (disableCertificateValidation)
            {
                ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); }
            }
            ;

            ServicePointManager.Expect100Continue = false;
            if (securityProtocolType.HasValue)
            {
                ServicePointManager.SecurityProtocol = securityProtocolType.Value;
            }

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

            httpWebRequest.Method                = requestMethod;
            httpWebRequest.ContentType           = "application/x-www-form-urlencoded";
            httpWebRequest.ContentLength         = data.Length;
            httpWebRequest.UseDefaultCredentials = true;

            if (certificate != null)
            {
                httpWebRequest.ClientCertificates.Add(certificate);
            }

            if (timeout.HasValue)
            {
                httpWebRequest.Timeout = httpWebRequest.ReadWriteTimeout = (int)timeout.Value.TotalMilliseconds;
            }

            var userInfo = httpWebRequest.Address.UserInfo;

            if (!string.IsNullOrEmpty(userInfo) && userInfo.Contains(':'))
            {
                httpWebRequest.Credentials     = new NetworkCredential(userInfo.Split(':').First(), userInfo.Split(':').Last());
                httpWebRequest.PreAuthenticate = true;
            }

            if (cookies != null)
            {
                httpWebRequest.CookieContainer = new CookieContainer();
                for (var i = 0; i < cookies.Count; i++)
                {
                    var currentCookie = cookies.Get(i);
                    if (currentCookie == null)
                    {
                        continue;
                    }

                    var cookie = new Cookie
                    {
                        Domain  = httpWebRequest.RequestUri.Host,
                        Expires = currentCookie.Expires,
                        Name    = currentCookie.Name,
                        Path    = currentCookie.Path,
                        Secure  = currentCookie.Secure,
                        Value   = currentCookie.Value
                    };

                    httpWebRequest.CookieContainer.Add(cookie);
                }
            }

            httpWebRequest.Accept = "*/*";
            foreach (var key in customHeaders.Keys)
            {
                if (key.Equals("content-type", StringComparison.InvariantCultureIgnoreCase))
                {
                    httpWebRequest.ContentType = customHeaders[key];
                }
                else if (key.Equals("transfer-encoding", StringComparison.InvariantCultureIgnoreCase))
                {
                    httpWebRequest.SendChunked      = true;
                    httpWebRequest.TransferEncoding = customHeaders[key];
                }
                else if (key.Equals("user-agent", StringComparison.InvariantCultureIgnoreCase))
                {
                    httpWebRequest.UserAgent = customHeaders[key];
                }
                else if (key.Equals("accept", StringComparison.InvariantCultureIgnoreCase))
                {
                    httpWebRequest.Accept = customHeaders[key];
                }
                else if (key.Equals("accept-encoding", StringComparison.InvariantCultureIgnoreCase))
                {
                    foreach (var decompress in customHeaders[key].Split(',').Select(s => s.Trim().ToLower()))
                    {
                        if (decompress == "deflate")
                        {
                            httpWebRequest.AutomaticDecompression |= DecompressionMethods.Deflate;
                        }
                        else if (decompress == "gzip")
                        {
                            httpWebRequest.AutomaticDecompression |= DecompressionMethods.GZip;
                        }
                    }
                }
                else
                {
                    httpWebRequest.Headers.Add(key, customHeaders[key]);
                }
            }

            try
            {
                if (data.Length > 0)
                {
                    using (var newStream = httpWebRequest.GetRequestStream())
                    {
                        newStream.Write(data, 0, data.Length);
                    }
                }

                using (var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
                {
                    using (var sr = new StreamReader(httpWebResponse.GetResponseStream()))
                    {
                        response = sr.ReadToEnd();
                        sr.Close();
                    }
                    httpWebResponse.Close();
                    responseHeaders = httpWebResponse.Headers.AllKeys.ToDictionary(k => k, k => httpWebResponse.Headers[k]);
                }
                return(HttpRequestResult.Success);
            }
            catch (WebException webEx)
            {
                using (var webResponse = webEx.Response)
                {
                    var httpResponse = (HttpWebResponse)webResponse;
                    if (webResponse != null)
                    {
                        using (var stream = webResponse.GetResponseStream())
                        {
                            var text = new StreamReader(stream).ReadToEnd();
                            response        = text.Trim().IfNullOrEmpty(httpResponse.StatusCode.ToString());
                            responseHeaders = webResponse.Headers.AllKeys.ToDictionary(k => k, k => webResponse.Headers[k]);
                            return(HttpRequestResult.WebException);
                        }
                    }

                    response = webEx.GetFullMessage();
                    return(HttpRequestResult.Exception);
                }
            }
            catch (Exception ex)
            {
                response = ex.GetFullMessage();
                return(HttpRequestResult.Exception);
            }
        }
Ejemplo n.º 9
0
    public static SqlXml clr_http_request(string requestMethod, string url, string parameters, string headersXml, string optionsXml)
    {
        ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);//验证服务器证书回调自动验证
        var debugXml = new XElement("Debug");

        debugXml.Add(GetDebugStepXElement("Starting",
                                          new XElement(
                                              "InputParameters",
                                              new XElement("requestMethod", requestMethod),
                                              new XElement("url", url),
                                              new XElement("parameters", parameters),
                                              new XElement("headersXml", headersXml),
                                              new XElement("optionsXml", optionsXml)
                                              )
                                          ));
        try
        {
            // Parse options, if any, into dictionary
            Dictionary <string, string> options = new Dictionary <string, string>();
            if (!string.IsNullOrWhiteSpace(optionsXml))
            {
                foreach (XElement element in XDocument.Parse(optionsXml).Descendants())
                {
                    options.Add(element.Name.LocalName, element.Value);
                }
            }
            debugXml.Add(GetDebugStepXElement("Parsed Options"));

            // Attempt to set SecurityProtocol if passed as option (i.e., Tls12,Tls11,Tls)
            if (options.ContainsKey("security_protocol"))
            {
                SecurityProtocolType?securityProtocol = null;
                foreach (var protocol in options["security_protocol"].Split(','))
                {
                    if (securityProtocol == null)
                    {
                        securityProtocol = (SecurityProtocolType)Enum.Parse(typeof(SecurityProtocolType), protocol);
                    }
                    else
                    {
                        securityProtocol = securityProtocol | (SecurityProtocolType)Enum.Parse(typeof(SecurityProtocolType), protocol);
                    }
                }
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)securityProtocol;
            }
            debugXml.Add(GetDebugStepXElement("Handled Option 'security_protocol'"));

            // If GET request, and there are parameters, build into url
            if (requestMethod.ToUpper() == "GET" && !string.IsNullOrWhiteSpace(parameters))
            {
                url += (url.IndexOf('?') > 0 ? "&" : "?") + parameters;
            }
            debugXml.Add(GetDebugStepXElement("Handled GET parameters"));

            // Create an HttpWebRequest with the url and set the method
            var request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = requestMethod.ToUpper();
            debugXml.Add(GetDebugStepXElement("Created HttpWebRequest object and set method"));

            // Add in any headers provided
            bool contentLengthSetFromHeaders = false;
            bool contentTypeSetFromHeaders   = false;
            if (!string.IsNullOrWhiteSpace(headersXml))
            {
                // Parse provided headers as XML and loop through header elements
                foreach (XElement headerElement in XElement.Parse(headersXml).Descendants())
                {
                    // Retrieve header's name and value
                    var headerName  = headerElement.Attribute("Name").Value;
                    var headerValue = headerElement.Value;

                    // Some headers cannot be set by request.Headers.Add() and need to set the HttpWebRequest property directly
                    switch (headerName)
                    {
                    case "Accept":
                        request.Accept = headerValue;
                        break;

                    case "Connection":
                        request.Connection = headerValue;
                        break;

                    case "Content-Length":
                        request.ContentLength       = long.Parse(headerValue);
                        contentLengthSetFromHeaders = true;
                        break;

                    case "Content-Type":
                        request.ContentType       = headerValue;
                        contentTypeSetFromHeaders = true;
                        break;

                    case "Date":
                        request.Date = DateTime.Parse(headerValue);
                        break;

                    case "Expect":
                        request.Expect = headerValue;
                        break;

                    case "Host":
                        request.Host = headerValue;
                        break;

                    case "If-Modified-Since":
                        request.IfModifiedSince = DateTime.Parse(headerValue);
                        break;

                    case "Range":
                        var parts = headerValue.Split('-');
                        request.AddRange(int.Parse(parts[0]), int.Parse(parts[1]));
                        break;

                    case "Referer":
                        request.Referer = headerValue;
                        break;

                    case "Transfer-Encoding":
                        request.TransferEncoding = headerValue;
                        break;

                    case "User-Agent":
                        request.UserAgent = headerValue;
                        break;

                    default:     // other headers
                        request.Headers.Add(headerName, headerValue);
                        break;
                    }
                }
            }
            debugXml.Add(GetDebugStepXElement("Processed Headers"));

            // Set the timeout if provided as an option
            if (options.ContainsKey("timeout"))
            {
                request.Timeout = int.Parse(options["timeout"]);
            }
            debugXml.Add(GetDebugStepXElement("Handled Option 'timeout'"));

            // Set the automatic decompression if provided as an option (default to Deflate | GZip)
            request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
            if (options.ContainsKey("auto_decompress") && bool.Parse(options["auto_decompress"]) == false)
            {
                request.AutomaticDecompression = DecompressionMethods.None;
            }
            debugXml.Add(GetDebugStepXElement("Handled Option 'auto_decompress'"));

            // Add in non-GET parameters provided
            if (requestMethod.ToUpper() != "GET" && !string.IsNullOrWhiteSpace(parameters))
            {
                // Convert to byte array
                var parameterData = Encoding.ASCII.GetBytes(parameters);

                // Set content info
                if (!contentLengthSetFromHeaders)
                {
                    request.ContentLength = parameterData.Length;
                }
                if (!contentTypeSetFromHeaders)
                {
                    request.ContentType = "application/x-www-form-urlencoded";
                }

                // Add data to request stream
                using (var stream = request.GetRequestStream())
                {
                    stream.Write(parameterData, 0, parameterData.Length);
                }
            }
            debugXml.Add(GetDebugStepXElement("Handled non-GET Parameters"));

            // Retrieve results from response
            XElement returnXml = null;
            try
            {
                debugXml.Add(GetDebugStepXElement("About to Send Request"));
                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    debugXml.Add(GetDebugStepXElement("Retrieved Response"));
                    // Get headers (loop through response's headers)
                    var responseHeadersXml = new XElement("Headers");
                    var responseHeaders    = response.Headers;
                    for (int i = 0; i < responseHeaders.Count; ++i)
                    {
                        // Get values for this header
                        var valuesXml = new XElement("Values");
                        foreach (string value in responseHeaders.GetValues(i))
                        {
                            valuesXml.Add(new XElement("Value", value));
                        }

                        // Add this header with its values to the headers xml
                        responseHeadersXml.Add(
                            new XElement("Header",
                                         new XElement("Name", responseHeaders.GetKey(i)),
                                         valuesXml
                                         )
                            );
                    }
                    debugXml.Add(GetDebugStepXElement("Processed Response Headers"));

                    // Get the response body
                    var responseString = String.Empty;
                    using (var stream = response.GetResponseStream())
                    {
                        // If requested to convert to base 64 string, use memory stream, otherwise stream reader
                        if (options.ContainsKey("convert_response_to_base64") && bool.Parse(options["convert_response_to_base64"]) == true)
                        {
                            using (var memoryStream = new MemoryStream())
                            {
                                // Copy response stream to memory stream
                                stream.CopyTo(memoryStream);

                                // Convert memory stream to a byte array
                                var bytes = memoryStream.ToArray();

                                // Convert to base 64 string
                                responseString = Convert.ToBase64String(bytes);
                            }
                        }
                        else
                        {
                            using (var reader = new StreamReader(stream))
                            {
                                // Retrieve response string
                                responseString = reader.ReadToEnd();

                                /* if(options.ContainsKey("url_decode") && bool.Parse(options["url_decode"]) == true)
                                 * {
                                 *   System.Text.Encoding.
                                 *   responseString = HttpUtility.UrlDecode(responseString);
                                 * }*/
                            }
                        }
                        debugXml.Add(GetDebugStepXElement("Handled Option 'convert_response_to_base64' and Retrieved Response Stream"));
                    }

                    // Assemble reponse XML from details of HttpWebResponse
                    returnXml =
                        new XElement("Response",
                                     new XElement("CharacterSet", response.CharacterSet),
                                     new XElement("ContentEncoding", response.ContentEncoding),
                                     new XElement("ContentLength", response.ContentLength),
                                     new XElement("ContentType", response.ContentType),
                                     new XElement("CookiesCount", response.Cookies.Count),
                                     new XElement("HeadersCount", response.Headers.Count),
                                     responseHeadersXml,
                                     new XElement("IsFromCache", response.IsFromCache),
                                     new XElement("IsMutuallyAuthenticated", response.IsMutuallyAuthenticated),
                                     new XElement("LastModified", response.LastModified),
                                     new XElement("Method", response.Method),
                                     new XElement("ProtocolVersion", response.ProtocolVersion),
                                     new XElement("ResponseUri", response.ResponseUri),
                                     new XElement("Server", response.Server),
                                     new XElement("StatusCode", response.StatusCode),
                                     new XElement("StatusNumber", ((int)response.StatusCode)),
                                     new XElement("StatusDescription", response.StatusDescription),
                                     new XElement("SupportsHeaders", response.SupportsHeaders),
                                     new XElement("Body", responseString)
                                     );
                    debugXml.Add(GetDebugStepXElement("Assembled Return Xml"));
                    if (options.ContainsKey("debug") && bool.Parse(options["debug"]) == true)
                    {
                        returnXml.Add(debugXml);
                    }
                }
            }
            catch (WebException we)
            {
                debugXml.Add(GetDebugStepXElement("WebException Encountered. See Exception for more detail"));
                // Check to see if we got a response
                if (we.Response != null)
                {
                    // If we got a response, generate return XML with the HTTP status code
                    HttpWebResponse errorResponse = we.Response as HttpWebResponse;
                    returnXml =
                        new XElement("Response",
                                     new XElement("Server", errorResponse.Server),
                                     new XElement("StatusCode", errorResponse.StatusCode),
                                     new XElement("StatusNumber", ((int)errorResponse.StatusCode)),
                                     new XElement("StatusDescription", errorResponse.StatusDescription),
                                     debugXml
                                     );
                }
                else
                {
                    // If there wasn't even a response then re-throw the exception since we didn't really want to catch it here
                    throw;
                }
            }

            // Return data
            return(new SqlXml(returnXml.CreateReader()));
        }
        catch (Exception ex)
        {
            debugXml.Add(GetDebugStepXElement("General Exception Encountered. See Exception for more detail"));

            // Return data
            return(new SqlXml((new XElement("Response", debugXml, GetXElementFromException(ex))).CreateReader()));
        }
    }