protected async Task <T> MakeRequestAsync <T, TIn>(HTTPMethod httpMethod, TIn model = null, EndpointMethod?route = null) where TIn : class where T : class, new()
        {
            using (var client = new HttpClient())
            {
                var uri     = new Uri($"{_endpoint}/{route?.ToString().ToLower()}");
                var json    = JsonConvert.SerializeObject(model);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                var request = new HttpRequestMessage
                {
                    RequestUri = uri,
                    Content    = content,
                    Method     = new HttpMethod(httpMethod.ToString())
                };
                HttpResponseMessage response = await client.SendAsync(request);

                string apiResponse = await response.Content.ReadAsStringAsync();

                try
                {
                    if (apiResponse != "")
                    {
                        return(JsonConvert.DeserializeObject <T>(apiResponse));
                    }
                    else if (response.StatusCode != System.Net.HttpStatusCode.Accepted)
                    {
                        throw new Exception();
                    }
                    return(new T());
                }
                catch (Exception ex)
                {
                    throw new Exception($"An error ocurred while calling the API. It responded with the following message: {response.StatusCode} {response.ReasonPhrase}");
                }
            }
        }
Esempio n. 2
0
 /// <summary>
 /// 短信配置
 /// </summary>
 /// <param name="appid">appid</param>
 /// <param name="appkey">appkey</param>
 /// <param name="httpMethod">请求方式</param>
 /// <param name="url">发送地址</param>
 public MessageConfig(string appid, string appkey, HTTPMethod httpMethod, string url)
 {
     this.appid  = appid;
     this.appkey = appkey;
     this.url    = url;
     this.method = httpMethod.ToString();
 }
Esempio n. 3
0
        /// <summary>
        ///     Helper method to create a web request with a lot of default settings
        /// </summary>
        /// <param name="uri">Uri with uri to connect to</param>
        /// <param name="method">Method to use</param>
        /// <returns>WebRequest</returns>
        public static HttpWebRequest CreateWebRequest(Uri uri, HTTPMethod method)
        {
            var webRequest = CreateWebRequest(uri);

            webRequest.Method = method.ToString();
            return(webRequest);
        }
Esempio n. 4
0
    /// <summary>
    /// HTTPMethod 를 분석하여 Request를 생성합니다.
    /// </summary>
    /// <returns> 생성된 Request 입니다. </returns>
    private Request CreateCurrentReq()
    {
        Request req = null;

        // HTTPMethod 테크
        switch (method)
        {
        // POST, PUT, DELETE 통신의 경우 url을 유지 하고 리퀘스트 생성시 필드데이터를 추가하여 생성합니다.
        case HTTPMethod.POST:
            req = new Request(method.ToString(), reqStr, GetFieldTable());
            break;

        case HTTPMethod.PUT:
            req = new Request(method.ToString(), reqStr, GetFieldTable());
            break;

        case HTTPMethod.DELETE:
            req = new Request(method.ToString(), reqStr, GetFieldTable());
            break;

        // GET 통신시 url에 파라미터를 조합하여 리퀘스트를 생성합니다.
        case HTTPMethod.GET:
            StringBuilder reqStringBuilder = new StringBuilder(reqStr);
            if (fieldDatas.Count != 0)
            {
                reqStringBuilder.Append("?");
                foreach (var data in fieldDatas)
                {
                    reqStringBuilder.Append("&").Append(data.Key).Append("=").Append(data.Value);
                }
            }
            req = new Request(method.ToString(), reqStringBuilder.ToString());
            break;

        case HTTPMethod.NONE:
            break;
        }

        if (req != null)
        {
            AddHeaderDatas(req);
        }

        return(req);
    }
Esempio n. 5
0
            public WWW www(string url, Dictionary <string, string> headers__WillBeMutated)
            {
                switch (method)
                {
                case HTTPMethod.GET:
                    return(new WWW(url, null, headers__WillBeMutated));

                case HTTPMethod.POST:
                    return(new WWW(url, body, headers__WillBeMutated));

                case HTTPMethod.DELETE:
                    headers__WillBeMutated["X-HTTP-Method-Override"] = method.ToString();
                    return(new WWW(url, null, headers__WillBeMutated));

                case HTTPMethod.PUT:
                    headers__WillBeMutated["X-HTTP-Method-Override"] = method.ToString();
                    return(new WWW(url, body, headers__WillBeMutated));

                default:
                    throw new IllegalStateException("Unreachable code");
                }
            }
        private void Creator(string url, HTTPMethod method, byte[] data = null)
        {
            this.Request   = WebRequest.CreateHttp(url);
            Request.Method = method.ToString();

            switch (method)
            {
            case HTTPMethod.Post:
                this.Request.ContentType = "application/x-www-form-urlencoded";
                break;
            }

            if (data != null)
            {
                Request.ContentLength = data.Length;
                Stream dataStream = Request.GetRequestStream();
                dataStream.Write(data, 0, data.Length);
                dataStream.Close();
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Init a ApiRequest object, that contain a HttpWebRequest object.
        /// </summary>
        /// <param name="uri">Request uri</param>
        /// <param name="method">HttpMethod</param>
        /// <param name="data">The requst body</param>
        /// <param name="contentType">Request content type</param>
        public ApiRequest(string uri, HTTPMethod method, byte[] data = null, string contentType = null)
        {
            this.Request   = WebRequest.Create(uri) as HttpWebRequest;
            Request.Method = method.ToString();

            if (!string.IsNullOrEmpty(contentType))
            {
                this.Request.ContentType = contentType;
            }

            if (data != null)
            {
                Stream dataStream = Request.GetRequestStream();
                dataStream.Write(data, 0, data.Length);
                dataStream.Close();
            }
            else
            {
                Request.ContentLength = 0;
            }
        }
Esempio n. 8
0
 public void SendRequst(HTTPMethod method, string url, string param, Action <string, string> callback, string body = null)
 {
     StartCoroutine(RequestProccess(method.ToString(), url + param, callback, body));
 }
Esempio n. 9
0
 public Controller(HTTPMethod method, RoutePatternMatch route, RouteCallback_D callback) :                   this(method.ToString(), route, route.CreateCallback(callback))
 {
 }
        private static Tuple <HttpStatusCode, string> MakeQrsRequest(string path, HTTPMethod method, HTTPContentType contentType = HTTPContentType.json, byte[] body = null)
        {
            // Fix Path
            if (!path.StartsWith("/"))
            {
                path = '/' + path;
            }
            if (path.EndsWith("/"))
            {
                path = path.Substring(0, path.Length - 1);
            }
            int indexOfSlash = path.LastIndexOf('/');
            int indexOfQuery = path.LastIndexOf('?');

            if (indexOfQuery <= indexOfSlash)
            {
                path += "?";
            }
            else
            {
                path += "&";
            }

            string         responseString = "";
            HttpStatusCode responseCode   = 0;

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

            //Create the HTTP Request and add required headers and content in xrfkey
            string         xrfkey  = "0123456789abcdef";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"https://*****:*****@"UserDirectory=internal;UserId=sa_api");
            // Add the certificate to the request and provide the user to execute as
            request.ClientCertificates.Add(SENSE_CERT.Value);

            if (method == HTTPMethod.POST || method == HTTPMethod.PUT)
            {
                // Set Headers
                if (contentType == HTTPContentType.json)
                {
                    request.ContentType = "application/json";
                }
                else if (contentType == HTTPContentType.app)
                {
                    request.ContentType = "application/vnd.qlik.sense.app";
                }
                else
                {
                    throw new ArgumentException("Content type '" + contentType.ToString() + "' is not supported.");
                }

                // Set Body
                if (body == null)
                {
                    request.ContentLength = 0;
                }
                else
                {
                    request.ContentLength = body.Length;
                    Stream requestStream = request.GetRequestStream();
                    requestStream.Write(body, 0, body.Length);
                    requestStream.Close();
                }
            }

            // make the web request and return the content
            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    responseCode = response.StatusCode;
                    using (Stream stream = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(stream))
                        {
                            // if response is invalid, throw exception and expect it to be handled in calling function (4xx errors)
                            responseString = JsonConvert.SerializeObject(reader.ReadToEnd());
                        }
                    }
                }
            }
            catch (WebException webEx)
            {
                return(new Tuple <HttpStatusCode, string>(HttpStatusCode.ServiceUnavailable, webEx.Message));
            }
            catch (Exception e)
            {
                return(new Tuple <HttpStatusCode, string>(HttpStatusCode.InternalServerError, e.Message));
            }

            return(new Tuple <HttpStatusCode, string>(responseCode, responseString));
        }
Esempio n. 11
0
 public Controller(HTTPMethod method, RoutePatternMatch route, Response res) :                               this(method.ToString(), route, route.CreateCallback(res))
 {
 }
        protected async Task <T> MakeRequestAsync <T>(HTTPMethod httpMethod, EndpointMethod?route = null, Dictionary <string, string> parameters = null) where T : class, new()
        {
            using (var client = new HttpClient())
            {
                var uri = new Uri($"{_endpoint}/{route?.ToString().ToLower()}");
                HttpRequestMessage requestMessage = new HttpRequestMessage(new HttpMethod(httpMethod.ToString()), uri);

                if (parameters != null)
                {
                    requestMessage.Content = new FormUrlEncodedContent(parameters);
                }

                HttpResponseMessage response = await client.SendAsync(requestMessage);

                string apiResponse = await response.Content.ReadAsStringAsync();

                try
                {
                    if (apiResponse != "" && !apiResponse.ToLower().Contains("message"))
                    {
                        return(JsonConvert.DeserializeObject <T>(apiResponse));
                    }
                    else if (response.StatusCode != System.Net.HttpStatusCode.Accepted)
                    {
                        throw new Exception();
                    }
                    return(new T());
                }
                catch (Exception ex)
                {
                    throw new Exception($"An error ocurred while calling the API. It responded with the following message: {response.StatusCode} {response.ReasonPhrase}");
                }
            }
        }
Esempio n. 13
0
        /// <summary>
        /// OAuth sign the parameters, meaning all oauth parameters are added to the supplied dictionary.
        /// And additionally a signature is added.
        /// </summary>
        /// <param name="method">Method (POST,PUT,GET)</param>
        /// <param name="requestURL">Url to call</param>
        /// <param name="parameters">IDictionary<string, string></param>
        private void Sign(HTTPMethod method, string requestURL, IDictionary<string, object> parameters)
        {
            if (parameters == null) {
                throw new ArgumentNullException("parameters");
            }
            // Build the signature base
            StringBuilder signatureBase = new StringBuilder();

            // Add Method to signature base
            signatureBase.Append(method.ToString()).Append("&");

            // Add normalized URL
            Uri url = new Uri(requestURL);
            string normalizedUrl = string.Format(CultureInfo.InvariantCulture, "{0}://{1}", url.Scheme, url.Host);
            if (!((url.Scheme == "http" && url.Port == 80) || (url.Scheme == "https" && url.Port == 443))) {
                normalizedUrl += ":" + url.Port;
            }
            normalizedUrl += url.AbsolutePath;
            signatureBase.Append(UrlEncode3986(normalizedUrl)).Append("&");

            // Add normalized parameters
            parameters.Add(OAUTH_VERSION_KEY, OAUTH_VERSION);
            parameters.Add(OAUTH_NONCE_KEY, GenerateNonce());
            parameters.Add(OAUTH_TIMESTAMP_KEY, GenerateTimeStamp());
            switch(SignatureType) {
                case OAuthSignatureTypes.RSASHA1:
                    parameters.Add(OAUTH_SIGNATURE_METHOD_KEY, RSASHA1SignatureType);
                    break;
                case OAuthSignatureTypes.PLAINTEXT:
                    parameters.Add(OAUTH_SIGNATURE_METHOD_KEY, PlainTextSignatureType);
                    break;
                case OAuthSignatureTypes.HMACSHA1:
                default:
                    parameters.Add(OAUTH_SIGNATURE_METHOD_KEY, HMACSHA1SignatureType);
                    break;
            }
            parameters.Add(OAUTH_CONSUMER_KEY_KEY, _consumerKey);
            if (CallbackUrl != null && RequestTokenUrl != null && requestURL.StartsWith(RequestTokenUrl)) {
                parameters.Add(OAUTH_CALLBACK_KEY, CallbackUrl);
            }
            if (!string.IsNullOrEmpty(Verifier)) {
                parameters.Add(OAUTH_VERIFIER_KEY, Verifier);
            }
            if (!string.IsNullOrEmpty(Token)) {
                parameters.Add(OAUTH_TOKEN_KEY, Token);
            }
            signatureBase.Append(UrlEncode3986(GenerateNormalizedParametersString(parameters)));
            LOG.DebugFormat("Signature base: {0}", signatureBase);
            string key = string.Format(CultureInfo.InvariantCulture, "{0}&{1}", UrlEncode3986(_consumerSecret), string.IsNullOrEmpty(TokenSecret) ? string.Empty : UrlEncode3986(TokenSecret));
            switch (SignatureType) {
                case OAuthSignatureTypes.RSASHA1:
                    // Code comes from here: http://www.dotnetfunda.com/articles/article1932-rest-service-call-using-oauth-10-authorization-with-rsa-sha1.aspx
                    // Read the .P12 file to read Private/Public key Certificate
                    string certFilePath = _consumerKey; // The .P12 certificate file path Example: "C:/mycertificate/MCOpenAPI.p12
                    string password = _consumerSecret; // password to read certificate .p12 file
                    // Read the Certification from .P12 file.
                    X509Certificate2 cert = new X509Certificate2(certFilePath.ToString(), password);
                    // Retrieve the Private key from Certificate.
                    RSACryptoServiceProvider RSAcrypt = (RSACryptoServiceProvider)cert.PrivateKey;
                    // Create a RSA-SHA1 Hash object
                    using (SHA1Managed shaHASHObject = new SHA1Managed()) {
                        // Create Byte Array of Signature base string
                        byte[] data = Encoding.ASCII.GetBytes(signatureBase.ToString());
                        // Create Hashmap of Signature base string
                        byte[] hash = shaHASHObject.ComputeHash(data);
                        // Create Sign Hash of base string
                        // NOTE - 'SignHash' gives correct data. Don't use SignData method
                        byte[] rsaSignature = RSAcrypt.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
                        // Convert to Base64 string
                        string base64string = Convert.ToBase64String(rsaSignature);
                        // Return the Encoded UTF8 string
                        parameters.Add(OAUTH_SIGNATURE_KEY, UrlEncode3986(base64string));
                    }
                    break;
                case OAuthSignatureTypes.PLAINTEXT:
                    parameters.Add(OAUTH_SIGNATURE_KEY, key);
                    break;
                case OAuthSignatureTypes.HMACSHA1:
                default:
                    // Generate Signature and add it to the parameters
                    HMACSHA1 hmacsha1 = new HMACSHA1();
                    hmacsha1.Key = Encoding.UTF8.GetBytes(key);
                    string signature = ComputeHash(hmacsha1, signatureBase.ToString());
                    parameters.Add(OAUTH_SIGNATURE_KEY, signature);
                    break;
            }
        }
Esempio n. 14
0
 /// <summary>
 /// Helper method to create a web request with a lot of default settings
 /// </summary>
 /// <param name="uri">Uri with uri to connect to</param>
 /// <param name="method">Method to use</param>
 /// <returns>WebRequest</returns>
 public static HttpWebRequest CreateWebRequest(Uri uri, HTTPMethod method)
 {
     HttpWebRequest webRequest = CreateWebRequest(uri);
     webRequest.Method = method.ToString();
     return webRequest;
 }
Esempio n. 15
0
 /// <summary>Sends an HTTP request.</summary>
 public static async Task <string> Request(HTTPMethod method, string url, string body, HTTPScheme scheme = HTTPScheme.HTTP) => await Request(method.ToString(), url, body, scheme);
Esempio n. 16
0
        public ClientResponse <RS, ERS> Go()
        {
            if (url.Length == 0)
            {
                throw new InvalidOperationException("You must specify a URL");
            }

            if (method == HTTPMethod.UNSET)
            {
                throw new InvalidOperationException("You must specify a HTTP method");
            }

            if (typeof(RS) != typeof(RESTVoid) && successResponseHandler == null)
            {
                throw new InvalidOperationException(
                          "You specified a success response type, you must then provide a success response handler.");
            }

            if (typeof(ERS) != typeof(RESTVoid) && errorResponseHandler == null)
            {
                throw new InvalidOperationException(
                          "You specified an error response type, you must then provide an error response handler.");
            }

            var response = new ClientResponse <RS, ERS>();

            response.request = (bodyHandler != null) ? bodyHandler.GetBodyObject() : null;
            response.method  = method;

            HttpWebRequest request;

            try
            {
                if (parameters.Count > 0)
                {
                    if (!url.ToString().Contains("?"))
                    {
                        url.Append("?");
                    }

                    foreach (var pair in parameters)
                    {
                        foreach (var value in pair.Value)
                        {
                            url.Append(HttpUtility.UrlEncode(pair.Key, Encoding.UTF8)).Append("=")
                            .Append(HttpUtility.UrlEncode(value.ToString(), Encoding.UTF8)).Append("&");
                        }
                    }

                    url.Remove(url.Length - 1, 1);
                }

                response.url = new Uri(url.ToString());
                request      = (HttpWebRequest)WebRequest.Create(response.url);

                if (webProxy != null)
                {
                    request.Proxy = webProxy;
                }

                // Handle SSL certificates
                if (response.url.Scheme.ToLower().Equals("https") && certificate != null)
                {
                    ServicePointManager.CertificatePolicy = new CertPolicy();
                    request.ClientCertificates.Add(certificate);
                }

                request.Timeout          = timeout;
                request.ReadWriteTimeout = readWriteTimeout;
                request.Method           = method.ToString();

                if (headers.Count > 0)
                {
                    foreach (var header in headers)
                    {
                        request.Headers[header.Key] = header.Value;
                    }
                }

                if (bodyHandler != null)
                {
                    bodyHandler.SetHeaders(request);
                }

                if (bodyHandler != null)
                {
                    using (var stream = request.GetRequestStream())
                    {
                        bodyHandler.Accept(stream);
                        stream.Flush();
                    }
                }
            }

            catch (Exception e)
            {
                logger.Debug("Error calling REST WebService at [" + url + "]", e);
                response.status    = -1;
                response.exception = e;
                return(response);
            }

            try
            {
                using (var resp = (HttpWebResponse)request.GetResponse())
                {
                    response.status = (int)resp.StatusCode;
                    if (successResponseHandler == null)
                    {
                        return(response);
                    }

                    try
                    {
                        using (var str = resp.GetResponseStream())
                        {
                            response.successResponse = successResponseHandler.Apply(str);
                        }
                    }
                    catch (Exception e)
                    {
                        logger.Debug("Error calling REST WebService at [" + url + "]", e);
                        response.status    = -1;
                        response.exception = e;
                        return(response);
                    }
                }
            }
            catch (WebException e)
            {
                response.status = -1;

                // The response will be null if the server couldn't be contacted, the connection broke, or
                // the communication with the server failed
                if (e.Response == null)
                {
                    response.exception = e;
                    return(response);
                }

                using (var webResp = e.Response)
                {
                    var httpResp = (HttpWebResponse)webResp;
                    response.status = (int)httpResp.StatusCode;

                    if (errorResponseHandler == null)
                    {
                        return(response);
                    }

                    try
                    {
                        using (var str = httpResp.GetResponseStream())
                        {
                            response.errorResponse = errorResponseHandler.Apply(str);
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Debug("Error calling REST WebService at [" + url + "]", e);
                        response.exception = ex;
                        return(response);
                    }
                }
            }

            return(response);
        }
Esempio n. 17
0
 public Controller(HTTPMethod method, string route, RouteCallback_A callback) :                              this(method.ToString(), route, callback)
 {
 }
Esempio n. 18
0
        /// <summary>
        /// Make the actual OAuth request, all oauth parameters are passed as header (default) and the others are placed in the url or post data.
        /// Any additional parameters added after the Sign call are not in the signature, this could be by design!
        /// </summary>
        /// <param name="method"></param>
        /// <param name="requestURL"></param>
        /// <param name="headers"></param>
        /// <param name="parameters"></param>
        /// <param name="postData">IBinaryParameter</param>
        /// <returns>Response from server</returns>
        private string MakeRequest(HTTPMethod method, string requestURL, IDictionary<string, string> headers, IDictionary<string, object> parameters, IBinaryContainer postData)
        {
            if (parameters == null) {
                throw new ArgumentNullException("parameters");
            }
            IDictionary<string, object> requestParameters;
            // Add oAuth values as HTTP headers, if this is allowed
            StringBuilder authHeader = null;
            if (UseHTTPHeadersForAuthorization) {
                authHeader = new StringBuilder();
                requestParameters = new Dictionary<string, object>();
                foreach (string parameterKey in parameters.Keys) {
                    if (parameterKey.StartsWith(OAUTH_PARAMETER_PREFIX)) {
                        authHeader.AppendFormat(CultureInfo.InvariantCulture, "{0}=\"{1}\", ", parameterKey, UrlEncode3986(string.Format("{0}",parameters[parameterKey])));
                    } else if (!requestParameters.ContainsKey(parameterKey)) {
                        requestParameters.Add(parameterKey, parameters[parameterKey]);
                    }
                }
                // Remove trailing comma and space and add it to the headers
                if (authHeader.Length > 0) {
                    authHeader.Remove(authHeader.Length - 2, 2);
                }
            } else {
                requestParameters = parameters;
            }

            if (HTTPMethod.GET == method || postData != null) {
                if (requestParameters.Count > 0) {
                    // Add the parameters to the request
                    requestURL += "?" + NetworkHelper.GenerateQueryParameters(requestParameters);
                }
            }
            // Create webrequest
            HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(requestURL);
            webRequest.Method = method.ToString();
            webRequest.ServicePoint.Expect100Continue = false;
            webRequest.UserAgent = _userAgent;
            webRequest.Timeout = 100000;

            if (UseHTTPHeadersForAuthorization && authHeader != null) {
                LOG.DebugFormat("Authorization: OAuth {0}", authHeader);
                webRequest.Headers.Add("Authorization: OAuth " + authHeader);
            }

            if (headers != null) {
                foreach(string key in headers.Keys) {
                    webRequest.Headers.Add(key, headers[key]);
                }
            }

            if ((HTTPMethod.POST == method || HTTPMethod.PUT == method) && postData == null && requestParameters.Count > 0) {
                if (UseMultipartFormData) {
                    NetworkHelper.WriteMultipartFormData(webRequest, requestParameters);
                } else {
                    StringBuilder form = new StringBuilder();
                    foreach (string parameterKey in requestParameters.Keys) {
                        if (parameters[parameterKey] is IBinaryContainer) {
                            IBinaryContainer binaryParameter = parameters[parameterKey] as IBinaryContainer;
                            form.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}&", UrlEncode3986(parameterKey), UrlEncode3986(binaryParameter.ToBase64String(Base64FormattingOptions.None)));
                        } else {
                            form.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}&", UrlEncode3986(parameterKey), UrlEncode3986(string.Format("{0}",parameters[parameterKey])));
                        }
                    }
                    // Remove trailing &
                    if (form.Length > 0) {
                        form.Remove(form.Length - 1, 1);
                    }
                    webRequest.ContentType = "application/x-www-form-urlencoded";
                    byte[] data = Encoding.UTF8.GetBytes(form.ToString());
                    using (var requestStream = webRequest.GetRequestStream()) {
                        requestStream.Write(data, 0, data.Length);
                    }
                }
            } else if (postData != null) {
                postData.Upload(webRequest);
            } else {
                webRequest.ContentLength = 0;
            }

            string responseData;
            try {
                responseData = NetworkHelper.GetResponse(webRequest);
                LOG.DebugFormat("Response: {0}", responseData);
            } catch (Exception ex) {
                LOG.Error("Couldn't retrieve response: ", ex);
                throw;
            } finally {
                webRequest = null;
            }

            return responseData;
        }
Esempio n. 19
0
        /// <summary>
        /// Make the actual OAuth request, all oauth parameters are passed as header (default) and the others are placed in the url or post data.
        /// Any additional parameters added after the Sign call are not in the signature, this could be by design!
        /// </summary>
        /// <param name="method"></param>
        /// <param name="requestURL"></param>
        /// <param name="headers"></param>
        /// <param name="parameters"></param>
        /// <param name="postData">IBinaryParameter</param>
        /// <returns>Response from server</returns>
        private string MakeRequest(HTTPMethod method, string requestURL, IDictionary <string, string> headers, IDictionary <string, object> parameters, IBinaryContainer postData)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            IDictionary <string, object> requestParameters;
            // Add oAuth values as HTTP headers, if this is allowed
            StringBuilder authHeader = null;

            if (UseHTTPHeadersForAuthorization)
            {
                authHeader        = new StringBuilder();
                requestParameters = new Dictionary <string, object>();
                foreach (string parameterKey in parameters.Keys)
                {
                    if (parameterKey.StartsWith(OAUTH_PARAMETER_PREFIX))
                    {
                        authHeader.AppendFormat(CultureInfo.InvariantCulture, "{0}=\"{1}\", ", parameterKey, UrlEncode3986(string.Format("{0}", parameters[parameterKey])));
                    }
                    else if (!requestParameters.ContainsKey(parameterKey))
                    {
                        requestParameters.Add(parameterKey, parameters[parameterKey]);
                    }
                }
                // Remove trailing comma and space and add it to the headers
                if (authHeader.Length > 0)
                {
                    authHeader.Remove(authHeader.Length - 2, 2);
                }
            }
            else
            {
                requestParameters = parameters;
            }

            if (HTTPMethod.GET == method || postData != null)
            {
                if (requestParameters.Count > 0)
                {
                    // Add the parameters to the request
                    requestURL += "?" + NetworkHelper.GenerateQueryParameters(requestParameters);
                }
            }
            // Create webrequest
            HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(requestURL);

            webRequest.Method = method.ToString();
            webRequest.ServicePoint.Expect100Continue = false;
            webRequest.UserAgent = _userAgent;
            webRequest.Timeout   = 100000;

            if (UseHTTPHeadersForAuthorization && authHeader != null)
            {
                LOG.DebugFormat("Authorization: OAuth {0}", authHeader);
                webRequest.Headers.Add("Authorization: OAuth " + authHeader);
            }

            if (headers != null)
            {
                foreach (string key in headers.Keys)
                {
                    webRequest.Headers.Add(key, headers[key]);
                }
            }

            if ((HTTPMethod.POST == method || HTTPMethod.PUT == method) && postData == null && requestParameters.Count > 0)
            {
                if (UseMultipartFormData)
                {
                    NetworkHelper.WriteMultipartFormData(webRequest, requestParameters);
                }
                else
                {
                    StringBuilder form = new StringBuilder();
                    foreach (string parameterKey in requestParameters.Keys)
                    {
                        if (parameters[parameterKey] is IBinaryContainer)
                        {
                            IBinaryContainer binaryParameter = parameters[parameterKey] as IBinaryContainer;
                            form.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}&", UrlEncode3986(parameterKey), UrlEncode3986(binaryParameter.ToBase64String(Base64FormattingOptions.None)));
                        }
                        else
                        {
                            form.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}&", UrlEncode3986(parameterKey), UrlEncode3986(string.Format("{0}", parameters[parameterKey])));
                        }
                    }
                    // Remove trailing &
                    if (form.Length > 0)
                    {
                        form.Remove(form.Length - 1, 1);
                    }
                    webRequest.ContentType = "application/x-www-form-urlencoded";
                    byte[] data = Encoding.UTF8.GetBytes(form.ToString());
                    using (var requestStream = webRequest.GetRequestStream()) {
                        requestStream.Write(data, 0, data.Length);
                    }
                }
            }
            else if (postData != null)
            {
                postData.Upload(webRequest);
            }
            else
            {
                webRequest.ContentLength = 0;
            }

            string responseData;

            try {
                responseData = NetworkHelper.GetResponse(webRequest);
                LOG.DebugFormat("Response: {0}", responseData);
            } catch (Exception ex) {
                LOG.Error("Couldn't retrieve response: ", ex);
                throw;
            } finally {
                webRequest = null;
            }

            return(responseData);
        }
Esempio n. 20
0
        /// <summary>
        /// OAuth sign the parameters, meaning all oauth parameters are added to the supplied dictionary.
        /// And additionally a signature is added.
        /// </summary>
        /// <param name="method">Method (POST,PUT,GET)</param>
        /// <param name="requestURL">Url to call</param>
        /// <param name="parameters">IDictionary<string, string></param>
        private void Sign(HTTPMethod method, string requestURL, IDictionary <string, object> parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            // Build the signature base
            StringBuilder signatureBase = new StringBuilder();

            // Add Method to signature base
            signatureBase.Append(method.ToString()).Append("&");

            // Add normalized URL
            Uri    url           = new Uri(requestURL);
            string normalizedUrl = string.Format(CultureInfo.InvariantCulture, "{0}://{1}", url.Scheme, url.Host);

            if (!((url.Scheme == "http" && url.Port == 80) || (url.Scheme == "https" && url.Port == 443)))
            {
                normalizedUrl += ":" + url.Port;
            }
            normalizedUrl += url.AbsolutePath;
            signatureBase.Append(UrlEncode3986(normalizedUrl)).Append("&");

            // Add normalized parameters
            parameters.Add(OAUTH_VERSION_KEY, OAUTH_VERSION);
            parameters.Add(OAUTH_NONCE_KEY, GenerateNonce());
            parameters.Add(OAUTH_TIMESTAMP_KEY, GenerateTimeStamp());
            switch (SignatureType)
            {
            case OAuthSignatureTypes.RSASHA1:
                parameters.Add(OAUTH_SIGNATURE_METHOD_KEY, RSASHA1SignatureType);
                break;

            case OAuthSignatureTypes.PLAINTEXT:
                parameters.Add(OAUTH_SIGNATURE_METHOD_KEY, PlainTextSignatureType);
                break;

            case OAuthSignatureTypes.HMACSHA1:
            default:
                parameters.Add(OAUTH_SIGNATURE_METHOD_KEY, HMACSHA1SignatureType);
                break;
            }
            parameters.Add(OAUTH_CONSUMER_KEY_KEY, _consumerKey);
            if (CallbackUrl != null && RequestTokenUrl != null && requestURL.StartsWith(RequestTokenUrl))
            {
                parameters.Add(OAUTH_CALLBACK_KEY, CallbackUrl);
            }
            if (!string.IsNullOrEmpty(Verifier))
            {
                parameters.Add(OAUTH_VERIFIER_KEY, Verifier);
            }
            if (!string.IsNullOrEmpty(Token))
            {
                parameters.Add(OAUTH_TOKEN_KEY, Token);
            }
            signatureBase.Append(UrlEncode3986(GenerateNormalizedParametersString(parameters)));
            LOG.DebugFormat("Signature base: {0}", signatureBase);
            string key = string.Format(CultureInfo.InvariantCulture, "{0}&{1}", UrlEncode3986(_consumerSecret), string.IsNullOrEmpty(TokenSecret) ? string.Empty : UrlEncode3986(TokenSecret));

            switch (SignatureType)
            {
            case OAuthSignatureTypes.RSASHA1:
                // Code comes from here: http://www.dotnetfunda.com/articles/article1932-rest-service-call-using-oauth-10-authorization-with-rsa-sha1.aspx
                // Read the .P12 file to read Private/Public key Certificate
                string certFilePath = _consumerKey;                        // The .P12 certificate file path Example: "C:/mycertificate/MCOpenAPI.p12
                string password     = _consumerSecret;                     // password to read certificate .p12 file
                // Read the Certification from .P12 file.
                X509Certificate2 cert = new X509Certificate2(certFilePath.ToString(), password);
                // Retrieve the Private key from Certificate.
                RSACryptoServiceProvider RSAcrypt = (RSACryptoServiceProvider)cert.PrivateKey;
                // Create a RSA-SHA1 Hash object
                using (SHA1Managed shaHASHObject = new SHA1Managed()) {
                    // Create Byte Array of Signature base string
                    byte[] data = Encoding.ASCII.GetBytes(signatureBase.ToString());
                    // Create Hashmap of Signature base string
                    byte[] hash = shaHASHObject.ComputeHash(data);
                    // Create Sign Hash of base string
                    // NOTE - 'SignHash' gives correct data. Don't use SignData method
                    byte[] rsaSignature = RSAcrypt.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
                    // Convert to Base64 string
                    string base64string = Convert.ToBase64String(rsaSignature);
                    // Return the Encoded UTF8 string
                    parameters.Add(OAUTH_SIGNATURE_KEY, UrlEncode3986(base64string));
                }
                break;

            case OAuthSignatureTypes.PLAINTEXT:
                parameters.Add(OAUTH_SIGNATURE_KEY, key);
                break;

            case OAuthSignatureTypes.HMACSHA1:
            default:
                // Generate Signature and add it to the parameters
                HMACSHA1 hmacsha1 = new HMACSHA1();
                hmacsha1.Key = Encoding.UTF8.GetBytes(key);
                string signature = ComputeHash(hmacsha1, signatureBase.ToString());
                parameters.Add(OAUTH_SIGNATURE_KEY, signature);
                break;
            }
        }
Esempio n. 21
0
        /// <summary>
        /// Creates a new HttpWebRequest based on the urlString, method and config.
        /// </summary>
        /// <param name="urlString">The urlString</param>
        /// <param name="method">The connection method</param>
        /// <returns>A new HttpWebRequest.</returns>
        private HttpWebRequest CreateConnection(string urlString, HTTPMethod method)
        {
            Uri url = new Uri(urlString);
            HttpWebRequest urlConnection = (System.Net.HttpWebRequest)WebRequest.Create(url);
            urlConnection.Method = method.ToString();
            urlConnection.ContentType = "application/xml";
            urlConnection.Credentials = new NetworkCredential(config.Username, config.Password);
            urlConnection.UserAgent = USER_AGENT_STRING;
            urlConnection.Timeout = config.RequestTimeout;
            urlConnection.ReadWriteTimeout = config.ReadWriteTimeout;

            if (config.UseGzip)
            {
                urlConnection.Headers.Add("Accept-Encoding", "gzip");
                urlConnection.Headers.Add("Content-Encoding", "gzip");
            }

            return urlConnection;
        }
Esempio n. 22
0
        public string Post(string url, HTTPMethod Method)// Custom Method
        {
            try
            {
                request = (HttpWebRequest)WebRequest.Create(url);
                if (Cookiereq.Count > 0)
                {
                    request.CookieContainer = Cookiereq;
                }
                if (UseProxy == true)
                {
                    request.Proxy = proxyip;
                }
                else
                {
                    request.Proxy = null;
                }
                request.Timeout     = Timeout;
                request.Method      = Method.ToString();
                request.ContentType = "application/x-www-form-urlencoded";
                if (CHeader.Count > 0)
                {
                    foreach (var Header in CHeader)
                    {
                        request.Headers[Header.Key] = Header.Value;
                    }
                }
                string data = null;
                if (Param.Count > 0)
                {
                    foreach (var item in Param)
                    {
                        data += item.Key + "=" + item.Value + "&";
                    }
                }

                byte[] dataToSend = Encoding.UTF8.GetBytes(data);
                request.ContentLength = dataToSend.Length;
                request.KeepAlive     = KeepAlive;
                request.Accept        = Accept;
                request.Headers.Add("Accept-Encoding", Accept_Encoding);
                request.Headers.Add("Accept-Language", Accept_Language);
                request.UserAgent = UserAgent;
                request.ServicePoint.Expect100Continue = Expect100Continue;
                request.ServicePoint.ConnectionLimit   = ConnectionLimit;
                request.ServicePoint.UseNagleAlgorithm = UseNagleAlgorithm;
                request.AllowAutoRedirect = AllowAutoRedirect;
                request.GetRequestStream().Write(dataToSend, 0, dataToSend.Length);
                response = (HttpWebResponse)request.GetResponse();
                using (Stream stream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        html = reader.ReadToEnd();
                    }
                }
                response.Close();
            }
            catch (WebException e)
            {
                response_error = e.Response;
                haserror       = true;

                response = (HttpWebResponse)response_error;

                using (Stream data1 = response.GetResponseStream())
                    using (var reader1 = new StreamReader(data1))
                    {
                        html = reader1.ReadToEnd();
                    }
            }
            return(html);
        }
Esempio n. 23
0
        /// <summary>
        /// Runs the request.
        /// </summary>
        /// <param name="url"> The url to send a request to. </param>
        /// <param name="methodType"> A method type. </param>
        /// <param name="errorHandler"> A callback to handle errors. </param>
        /// <param name="callback"> A callback to handle a succesful request. Null by default. </param>
        /// <param name="query"> A set of query parameters. Null by default. </param>
        /// <param name="body"> A byte array. </param>
        /// <param name="contentType"> A content type of this request. If left the value null, the contentType will be "application/json". </param>
        public static void RunRequest(string url, HTTPMethod methodType, RequestErrorCallback errorHandler,
                                      RequestResultCallback callback = null, MoBackRequestParameters query = null,
                                      byte[] body = null, string contentType = null)
        {
            WebRequest request;

            if (query != null)
            {
                request = WebRequest.Create(url + query);
            }
            else
            {
                request = WebRequest.Create(url);
            }

            if (MoBack.MoBackAppSettings.loggingLevel >= MoBackAppSettings.LoggingLevel.VERBOSE)
            {
                Debug.Log(request.RequestUri.AbsoluteUri);
            }

            // Insert keys
            WebHeaderCollection collection = new WebHeaderCollection();

            collection.Add("X-Moback-Application-Key", MoBack.MoBackAppSettings.ApplicationID);
            collection.Add("X-Moback-Environment-Key", MoBack.MoBackAppSettings.EnvironmentKey);

            // Set session token if there is one.
            if (!string.IsNullOrEmpty(MoBack.MoBackAppSettings.SessionToken))
            {
                collection.Add("X-Moback-SessionToken-Key", MoBack.MoBackAppSettings.SessionToken);
            }

            request.Headers = collection;

            // Specify request as GET, POST, PUT, or DELETE
            request.Method = methodType.ToString();

            if (string.IsNullOrEmpty(contentType))
            {
                request.ContentType = "application/json";
            }
            else
            {
                request.ContentType = contentType;
            }
            // Specify request content length
            request.ContentLength = body == null ? 0 : body.Length;

            string responseFromServer = String.Empty;

            #if UNITY_ANDROID && !UNITY_EDITOR
            ServicePointManager.ServerCertificateValidationCallback = SSLValidator.Validator;
            #elif UNITY_EDITOR_WIN || (UNITY_STANDALONE_WIN && !UNITY_EDITOR_OSX)
            ServicePointManager.ServerCertificateValidationCallback = Validator;
            #endif

            try
            {
                // Open a stream and send the request to the remote server
                Stream dataStream = null;
                if (body != null)
                {
                    dataStream = request.GetRequestStream();
                    dataStream.Write(body, 0, body.Length);
                    dataStream.Close();
                }

                // Complete the request, wait for and accept any response
                WebResponse response = request.GetResponse();
                // Process response
                if (MoBackAppSettings.loggingLevel >= MoBackAppSettings.LoggingLevel.VERBOSE)
                {
                    Debug.Log(((HttpWebResponse)response).StatusDescription);
                }
                dataStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream);
                responseFromServer = reader.ReadToEnd();
                // Debug.Log("the json is "+responseFromServer.ToString());
                // Close all streams
                reader.Close();
                response.Close();
            }
            catch (WebException webException)
            {
                HttpWebResponse errorResponse = webException.Response as HttpWebResponse;
                if (errorResponse != null)
                {
                    if (MoBackAppSettings.loggingLevel >= MoBackAppSettings.LoggingLevel.WARNINGS)
                    {
                        Debug.LogWarning(string.Format("Network Request Error {0}: {1}.\nFull Exception: {2}", (int)errorResponse.StatusCode, errorResponse.StatusCode.ToString(), MoBackError.FormatException(webException)));
                    }
                    errorHandler(webException, webException.Status, errorResponse.StatusCode, webException.Message);
                }
                else
                {
                    if (MoBackAppSettings.loggingLevel >= MoBackAppSettings.LoggingLevel.WARNINGS)
                    {
                        Debug.LogWarning(string.Format("Network Request Failed with message {0}.\nFull exception: {1}", webException.Message, MoBackError.FormatException(webException)));
                    }
                    errorHandler(webException, webException.Status, null, webException.Message);
                }
                return;
            }

            if (MoBackAppSettings.loggingLevel >= MoBackAppSettings.LoggingLevel.VERBOSE)
            {
                Debug.Log(responseFromServer);
            }
            if (callback != null)
            {
                SimpleJSONNode responseAsJSON = SimpleJSONNode.Parse(responseFromServer);

                callback(responseFromServer, responseAsJSON);
            }
        }