Example #1
0
        public void MakeCall(RequestMethod method, string path, string data, Dictionary <string, string> headers, ApiCallCallback callback)
        {
            if (_baseHost == null)
            {
                DevLogger.Error(string.Format("Need initialize {0} before MakeCall",
                                              GetType()), MarketLogType.MarketApi);
                return;
            }
            var uri = new Uri(_baseHost, path);

            Log(string.Format("{0} request: {1} \n{2}", method.ToString().ToUpper(),
                              GetShortUrl(uri.ToString()), data));
            switch (method)
            {
            case RequestMethod.Get:
                StartCoroutine(MakeGet(uri, headers, callback, _apiSettings.UseDebug));
                break;

            case RequestMethod.Post:
                StartCoroutine(MakePost(uri, data, headers, callback, _apiSettings.UseDebug));
                break;

            case RequestMethod.Put:
                StartCoroutine(MakePut(uri, data, headers, callback, _apiSettings.UseDebug));
                break;

            default:
                throw new ArgumentOutOfRangeException("method", method, null);
            }
        }
Example #2
0
        public static string SendRequestWithHeader(string apiUrl, RequestMethod method, Dictionary <string, string> headerData)
        {
            string jsonStr = "";

            try
            {
                HttpWebRequest request = WebRequest.Create(apiUrl) as HttpWebRequest;
                request.Method = method.ToString().ToUpper();

                foreach (var item in headerData)
                {
                    request.Headers.Add(item.Key, item.Value);
                }

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;

                using (Stream receiveStream = response.GetResponseStream())
                {
                    using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
                    {
                        jsonStr = readStream.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(jsonStr);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="requestMethod"></param>
        /// <param name="url"></param>
        /// <param name="authorisationToken"></param>
        /// <param name="navigationPage"></param>
        /// <param name="navigationPageSize"></param>
        /// <returns></returns>
        private static HttpWebRequest CreateHttpWebRequest(RequestMethod requestMethod, string url, string authorisationToken, int?navigationPage = null, int?navigationPageSize = null, string methodOverride = null)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.ContentType = "application/xml";
            request.Method      = requestMethod.ToString();
            request.KeepAlive   = false;
            request.Accept      = "application/xml";
            request.Headers.Add("Authorization", authorisationToken);

            if (navigationPage.HasValue)
            {
                request.Headers.Add("navigationPage", navigationPage.Value.ToString());
            }

            if (navigationPageSize.HasValue)
            {
                request.Headers.Add("navigationPageSize", navigationPageSize.Value.ToString());
            }

            if (!String.IsNullOrWhiteSpace(methodOverride))
            {
                request.Headers.Add("X-HTTP-Method-Override", methodOverride.Trim());
            }

            return(request);
        }
        public static Method Map(RequestMethod method)
        {
            Method mthd;
            Enum.TryParse(method.ToString().ToUpperInvariant(), out mthd);

            return mthd;
        }
Example #5
0
        /// <summary>
        /// 新建并初始化一个Http请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="method">请求方法</param>
        private void Create(string url, RequestMethod method)
        {
            _Request             = (HttpWebRequest)WebRequest.Create(url);
            _Request.Method      = method.ToString();
            _Request.Accept      = "application/json";
            _Request.ContentType = ContentType;
            if (_Token != null)
            {
                _Request.Headers.Add(HttpRequestHeader.Authorization, _Token);
            }

            if (AcceptEncoding != CompressType.None)
            {
                _Request.Headers.Add(HttpRequestHeader.AcceptEncoding, AcceptEncoding.ToString().ToLower());
            }

            if (ContentEncoding != CompressType.None)
            {
                _Request.Headers.Add(HttpRequestHeader.ContentEncoding, ContentEncoding.ToString().ToLower());
            }

            if (Headers == null)
            {
                return;
            }

            foreach (var header in Headers)
            {
                _Request.Headers[header.Key] = header.Value;
            }
        }
        public static APIOperation Create(string name,
                                          RequestMethod method, string urlTemplate,
                                          ParameterContract[] parameters,
                                          RequestContract request, ResponseContract[] responses, string description = null)
        {
            if (String.IsNullOrWhiteSpace(name))
            {
                throw new InvalidEntityException("Operation's is required");
            }
            if (name.Length > 100)
            {
                throw new InvalidEntityException("Length of operation's name must be < 100");
            }
            if (String.IsNullOrWhiteSpace(urlTemplate))
            {
                throw new InvalidEntityException("Operation's urlTemplate is required");
            }


            APIOperation operation = new APIOperation();

            operation.Id                 = EntityIdGenerator.GenerateIdSignature(Constants.IdPrefixTemplate.APIOPERATION);
            operation.Name               = name;
            operation.Method             = method.ToString();
            operation.TemplateParameters = parameters;
            operation.Request            = request;
            operation.Responses          = responses;
            operation.Description        = description;

            operation.UrlTemplate = urlTemplate;
            //operation.UrlTemplate = APIOperationHelper.BuildURL(urlTemplate, parameters);

            return(operation);
        }
Example #7
0
 public override void Execute()
 {
     try
     {
         string requestBody = GetRequestBody();
         statusCode = HttpStatusCode.OK;
         if (requestBody.Contains("GetUpdatedFormDigestInformation"))
         {
             responseString      = DigestResponse;
             responseContentType = "text/xml";
         }
         else
         {
             responseString = ResponseProvider.GetResponse(RequestUrl, RequestMethod.ToString(), requestBody);
             //remove duplicated escape characters (possible due to anonymous guid serializtion)
             responseString = responseString.Replace("\\\\/", "\\/");
             //however add \ for Guids and Dates the expectedformat is Id: "\/Guid(...)\/"
             responseString      = responseString.Replace("\"/Guid(", "\"\\/Guid(");
             responseString      = responseString.Replace("\"/Date(", "\"\\/Date(");
             responseString      = responseString.Replace(")/\"", ")\\/\"");
             responseContentType = "application/json";
         }
     }
     catch (Exception ex)
     {
         statusCode     = HttpStatusCode.InternalServerError;
         responseString = ex.Message;
     }
     ResponseStream = new MemoryStream(Encoding.UTF8.GetBytes(responseString));
 }
Example #8
0
        /// <summary>
        /// General Upload function to perform POST, PUT and DELETE
        /// </summary>
        /// <param name="httpMethod">POST, PUT, DELETE</param>
        protected (string rxdata, string error) Upload(RequestMethod requestMethod, string apiPath, string json)
        {
            string httpMethod = requestMethod.ToString();

            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri(_APIUrl);

                (string rxdata, string error)result = (null, null);

                var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
                stringContent.Headers.Add("APIToken", _APIToken);

                var _httpMethod = new HttpMethod(httpMethod);
                var request     = new HttpRequestMessage(_httpMethod, apiPath);
                request.Content = stringContent;

                var response = httpClient.SendAsync(request).Result;

                if (response.IsSuccessStatusCode)
                {
                    using (HttpContent content = response.Content)
                    {
                        result.rxdata = content.ReadAsStringAsync().Result;
                    }
                }
                else
                {
                    result.error = response.StatusCode.ToString() + " - " + response.ReasonPhrase;
                }

                return(result);
            }
        }
Example #9
0
        protected void CreateHttpClient(RequestMethod requestMethod, string url, Tuple <string, string>[] dataParameters, Tuple <string, string>[] urlParameters, out HttpClient client, out HttpRequestMessage requestMessage)
        {
            var method  = new HttpMethod(requestMethod.ToString());
            var handler = new HttpClientHandler()
            {
                Credentials     = new NetworkCredential(UAS.User, UAS.Password),
                CookieContainer = CookieContainer,
                UseCookies      = true,
                UseProxy        = false,
                ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) => { return(true); }
            };

            client = new HttpClient(handler);

            requestMessage = new HttpRequestMessage(method, BuildUri(url, urlParameters));
            requestMessage.Headers.Remove("Accept");
            requestMessage.Headers.Add("Accept", AcceptHeader);

            switch (requestMethod)
            {
            case RequestMethod.GET:


                break;

            default:
                if (dataParameters != null)
                {
                    requestMessage.Content = new StringContent(BuildDataParameters(dataParameters), Encoding.UTF8);
                    requestMessage.Content.Headers.Remove("Content-Type");
                    requestMessage.Content.Headers.Add("Content-Type", ContentTypeHeader);
                }
                break;
            }
        }
Example #10
0
        /// <summary>
        /// The make request.
        /// </summary>
        /// <param name="method">
        /// The method.
        /// </param>
        /// <param name="contentType">
        /// The content type. i.e. application/json, text/plain.
        /// </param>
        /// <param name="url">
        /// The url.
        /// </param>
        /// <param name="postData">
        /// The post data.
        /// </param>
        /// <param name="token">
        /// The token.
        /// </param>
        /// <returns>
        /// The <see cref="HttpWebResponse"/>.
        /// </returns>
        private static HttpWebResponse MakeRequest(RequestMethod method, string contentType, string url, string postData = "", string token = "")
        {
            var request = (HttpWebRequest)WebRequest.Create(url);
            var data    = Encoding.ASCII.GetBytes(postData);

            request.Method        = method.ToString().ToUpper();
            request.ContentType   = contentType;
            request.ContentLength = data.Length;
            request.Timeout       = 60000;

            if (!string.IsNullOrEmpty(token))
            {
                request.Headers[HttpRequestHeader.Authorization] = string.Format("Bearer {0}", token);
            }

            try
            {
                if (request.Method == "POST")
                {
                    using (var stream = request.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
                }

                var response = (HttpWebResponse)request.GetResponse();

                return(response);
            }
            catch (WebException ex)
            {
                return((HttpWebResponse)ex.Response);
            }
        }
        public void DefaultToStringGetHashCode()
        {
            RequestMethod method = default;

            Assert.AreEqual(0, method.GetHashCode());
            Assert.AreEqual("<null>", method.ToString());
        }
Example #12
0
        /// <summary>
        /// Wraps a web request into a convenient package.
        /// </summary>
        /// <param name="method">HTTP method of the request.</param>
        /// <param name="url">Full URL to the web resource.</param>
        /// <param name="postData">Data to post in query string format.</param>
        /// <returns>The web server response.</returns>
        private string MakeWebRequest(RequestMethod method,
                                      string url,
                                      List <IQueryParameter <string> > parameters,
                                      string postData)
        {
            var responseData = string.Empty;

            ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            ServicePointManager.CertificatePolicy = new CertificateManager();

            // TODO: Set UserAgent, Timeout, KeepAlive, Proxy?
            HttpWebRequest webRequest = ProxiedWebRequest.Create(url);

            webRequest.Method = method.ToString();
            webRequest.ServicePoint.Expect100Continue = false;

            var headerParams =
                parameters.Implode(",", q => string.Format("{0}=\"{1}\"", q.Name, q.Value));

            if (Debugging)
            {
                Logger.Debug("Generated auth header params string: " + headerParams);
            }
            webRequest.Headers.Add("Authorization",
                                   String.Format("OAuth realm=\"{0}\",{1}",
                                                 Realm, headerParams));
            if (postData == null)
            {
                postData = string.Empty;
            }

            if (method == RequestMethod.PUT ||
                method == RequestMethod.POST)
            {
                webRequest.ContentType = "application/json";
                // TODO: Error handling?
                using (var requestWriter = new StreamWriter(webRequest.GetRequestStream()))
                    requestWriter.Write(postData);
            }

            try {
                using (var responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream())) {
                    responseData = responseReader.ReadToEnd();
                }
            } catch (Exception e) {
                Logger.Error("Caught exception. Message: {0}", e.Message);
                Logger.Error("Stack trace for previous exception: {0}", e.StackTrace);
                Logger.Error("Rest of stack trace for above exception: {0}", System.Environment.StackTrace);
                throw;
            }

            if (Debugging)
            {
                Logger.Debug("Made web request, got response: {0}", responseData);
            }

            return(responseData);
        }
Example #13
0
        public override async Task <string> SendHttpClientRequest <T>(string endpoint, RequestMethod method, T requestBody, Dictionary <string, string> parms = null)
        {
            HttpWebRequest httpWebRequest = null;

            try
            {
                httpWebRequest = (HttpWebRequest)WebRequest.Create(WcUrl + AttachParameters(endpoint, parms));

                // start the stream immediately
                httpWebRequest.Method = method.ToString();
                httpWebRequest.AllowReadStreamBuffering = false;

                if (webRequestFilter != null)
                {
                    webRequestFilter.Invoke(httpWebRequest);
                }

                if (requestBody.GetType() != typeof(string))
                {
                    httpWebRequest.ContentType = "application/json";
                    var    buffer     = Encoding.UTF8.GetBytes(SerializeJSon(requestBody));
                    Stream dataStream = await httpWebRequest.GetRequestStreamAsync().ConfigureAwait(false);

                    dataStream.Write(buffer, 0, buffer.Length);
                }

                // asynchronously get a response
                WebResponse wr = await httpWebRequest.GetResponseAsync().ConfigureAwait(false);

                if (webResponseFilter != null)
                {
                    webResponseFilter.Invoke((HttpWebResponse)wr);
                }

                return(await GetStreamContent(wr.GetResponseStream(), wr.ContentType.Contains("=")?wr.ContentType.Split('=')[1] : "UTF-8").ConfigureAwait(false));
            }
            catch (WebException we)
            {
                if (httpWebRequest != null && httpWebRequest.HaveResponse)
                {
                    if (we.Response != null)
                    {
                        throw new WooCommerceException(await GetStreamContent(we.Response.GetResponseStream(), we.Response.ContentType.Contains("=") ? we.Response.ContentType.Split('=')[1] : "UTF-8").ConfigureAwait(false), we.InnerException);
                    }
                    else
                    {
                        throw;
                    }
                }
                else
                {
                    throw;
                }
            }
            catch (Exception e)
            {
                throw new WooCommerceException(e.Message, e.InnerException);
            }
        }
Example #14
0
        /// <summary>
        /// Make Restful calls
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="endpoint"></param>
        /// <param name="method">HEAD, GET, POST, PUT, PATCH, DELETE</param>
        /// <param name="requestBody">If your call doesn't have a body, please pass string.Empty, not null.</param>
        /// <param name="parms"></param>
        /// <returns>json string</returns>
        public async Task <string> SendHttpClientRequest <T>(string endpoint, RequestMethod method, T requestBody, Dictionary <string, string> parms = null)
        {
            HttpWebRequest httpWebRequest = null;

            try
            {
                httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(wc_url + GetOAuthEndPoint(method.ToString(), endpoint, parms));
                if (wc_url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    //httpWebRequest.Credentials = new NetworkCredential(wc_key, wc_secret);
                    httpWebRequest.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(wc_key + ":" + wc_secret));
                }

                // start the stream immediately
                httpWebRequest.Method      = method.ToString();
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.AllowReadStreamBuffering = false;

                //if (wc_Proxy)
                //    httpWebRequest.Proxy.Credentials = CredentialCache.DefaultCredentials;
                //else
                //    httpWebRequest.Proxy = null;

                if (requestBody.GetType() != typeof(string))
                {
                    var    buffer     = UTF8Encoding.UTF8.GetBytes(SerializeJSon(requestBody));
                    Stream dataStream = await httpWebRequest.GetRequestStreamAsync();

                    dataStream.Write(buffer, 0, buffer.Length);
                }

                // asynchronously get a response
                WebResponse wr = await httpWebRequest.GetResponseAsync();

                return(await GetStreamContent(wr.GetResponseStream(), wr.ContentType.Split('=')[1]));
            }
            catch (WebException we)
            {
                if (httpWebRequest != null && httpWebRequest.HaveResponse)
                {
                    if (we.Response != null)
                    {
                        throw new Exception(await GetStreamContent(we.Response.GetResponseStream(), we.Response.ContentType.Split('=')[1]));
                    }
                    else
                    {
                        throw we;
                    }
                }
                else
                {
                    throw we;
                }
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }
        private HttpWebRequest GenerateRequest(string uri, string content, RequestMethod method, string login, string password, bool allowAutoRedirect, string contentType, HeadersDto headers)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }
            if (string.IsNullOrEmpty(contentType))
            {
                contentType = "application/x-www-form-urlencoded";
            }
            // Create a request using a URL that can receive a post.
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);

            // Set the Method property of the request to POST.
            request.Method            = method.ToString();
            request.AllowAutoRedirect = allowAutoRedirect;
            //Default proxy does not work thats why set to null
            request.Proxy = null;
            //request.Credentials = new NetworkCredential("muhammads", "Leo4580@");
            //request.Proxy.Credentials = new NetworkCredential("muhammads", "Leo4580@");

            if (headers != null)
            {
                if (headers.Headers?.Count > 0)
                {
                    foreach (var header in headers.Headers)
                    {
                        request.Headers.Add(header.Name + " " + header.Value);
                    }
                }
            }

            // If login is empty use defaul credentials
            if (string.IsNullOrEmpty(login))
            {
                request.Credentials = CredentialCache.DefaultNetworkCredentials;
            }
            else
            {
                request.Credentials = new NetworkCredential(login, password);
            }
            if (method == RequestMethod.Post)
            {
                // Convert POST data to a byte array.
                byte[] byteArray = Encoding.UTF8.GetBytes(content);
                // Set the ContentType property of the WebRequest.
                request.ContentType = contentType;
                // Set the ContentLength property of the WebRequest.
                request.ContentLength = byteArray.Length;
                // Get the request stream.
                Stream dataStream = request.GetRequestStream();
                // Write the data to the request stream.
                dataStream.Write(byteArray, 0, byteArray.Length);
                // Close the Stream object.
                dataStream.Close();
            }
            return(request);
        }
Example #16
0
        string GetRequestMethod()
        {
            if (!RequestMethod.HasValue)
            {
                return(UrlRequestMethod.GET.ToString());
            }

            return(RequestMethod.ToString());
        }
        /// <summary>
        /// Make Restful calls
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="endpoint"></param>
        /// <param name="method">HEAD, GET, POST, PUT, PATCH, DELETE</param>
        /// <param name="requestBody">If your call doesn't have a body, please pass string.Empty, not null.</param>
        /// <param name="parms"></param>
        /// <returns>json string</returns>
        public async Task <string> SendHttpClientRequest <T>(string endpoint, RequestMethod method, T requestBody, Dictionary <string, string> parms = null)
        {
            HttpWebRequest httpWebRequest = null;

            try
            {
                httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(wc_url + GetOAuthEndPoint(method.ToString(), endpoint, parms));
                //if (!string.IsNullOrEmpty(username) || !string.IsNullOrEmpty(password))
                //{
                //    httpWebRequest.Credentials = new NetworkCredential(username, password);
                //}

                // start the stream immediately
                httpWebRequest.Method      = method.ToString();
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.AllowReadStreamBuffering = false;
                //if (wc_Proxy)
                //    httpWebRequest.Proxy.Credentials = CredentialCache.DefaultCredentials;
                //else
                //    httpWebRequest.Proxy = null;

                if (requestBody.GetType() != typeof(string))
                {
                    var    buffer     = UTF8Encoding.UTF8.GetBytes(SerializeJSon(requestBody));
                    Stream dataStream = await httpWebRequest.GetRequestStreamAsync();

                    dataStream.Write(buffer, 0, buffer.Length);
                }

                // asynchronously get a response
                WebResponse wr = await httpWebRequest.GetResponseAsync();

                return(await GetStreamContent(wr.GetResponseStream(), wr.ContentType.Split('=')[1]));
            }
            catch (WebException we)
            {
                if (httpWebRequest != null && httpWebRequest.HaveResponse)
                {
                    if (we.Response != null)
                    {
                        throw new Exception(await GetStreamContent(we.Response.GetResponseStream(), we.Response.ContentType.Split('=')[1]));
                    }
                    else
                    {
                        throw we;
                    }
                }
                else
                {
                    throw we;
                }
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }
Example #18
0
        public void TestCreateAPIOperation()
        {
            long   c1, c2;
            string apiId = _apiId1;

            RequestMethod method      = RequestMethod.DELETE;
            string        name        = method.ToString() + " Calc operation";
            string        urlTemplate = "/calc/" + method.ToString();
            string        description = "";

            APIOperation operation = APIOperation.Create(name, method, urlTemplate, null, null, null, description, _operationId1);

            c1 = Client.GetOperationsByAPIAsync(apiId).Result.Count;
            APIOperation entity = Client.CreateAPIOperationAsync(apiId, operation).Result;

            c2 = Client.GetOperationsByAPIAsync(apiId).Result.Count;
            Assert.AreEqual(c1 + 1, c2);
        }
Example #19
0
 public HtmlForm(RequestMethod method, string action, IDictionary<string, string> errors = null)
     : base("form", null)
 {
     SetAttribut("name", "form");
     SetAttribut("method", method.ToString());
     SetAttribut("action", action);
     SetAttribut("onsubmit", "return FormIsValid()");
     _errors = errors;
 }
Example #20
0
        //public static HttpWebRequest BuildHttpWebRequest(HttpRequestBase request, string url, int timeoutInSecond)
        //{
        //    if (request == null)
        //        return null;

        //    HttpWebRequest httpReq = WebRequest.Create(url) as HttpWebRequest;
        //    if (request.IsSecureConnection)
        //    {
        //        ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; };
        //        httpReq.ProtocolVersion = HttpVersion.Version10;
        //    }

        //    //注意:HttpWebRequire.Method默认为Get,
        //    //在写入请求前必须把HttpWebRequire.Method设置为Post,
        //    //否则在使用BeginGetRequireStream获取请求数据流的时候,系统就会发出“无法发送具有此谓词类型的内容正文”的异常。
        //    httpReq.Method = request.HttpMethod;

        //    // Copy unrestricted headers (including cookies, if any)
        //    //foreach (string headerKey in request.Headers.AllKeys)
        //    //{
        //    //    switch (headerKey)
        //    //    {
        //    //        case "Connection":
        //    //        case "Content-Length":
        //    //        case "Date":
        //    //        case "Expect":
        //    //        case "Host":
        //    //        case "If-Modified-Since":
        //    //        case "Range":
        //    //        case "Transfer-Encoding":
        //    //        case "Proxy-Connection":
        //    //            // Let IIS handle these
        //    //            break;
        //    //        case "Accept":
        //    //        case "Content-Type":
        //    //        case "Referer":
        //    //        case "User-Agent":
        //    //        //case "Cookie":
        //    //        case "Cache-Control":
        //    //            // Restricted - copied below
        //    //            break;
        //    //        default:
        //    //            httpReq.Headers[headerKey] = request.Headers[headerKey];
        //    //            break;
        //    //    }
        //    //}
        //    httpReq.ServicePoint.Expect100Continue = false;
        //    httpReq.Timeout = timeoutInSecond * 1000;
        //    // Copy restricted headers
        //    if (!request.AcceptTypes.IsNullOrEmpty())
        //    {
        //        httpReq.Accept = string.Join(",", request.AcceptTypes);
        //    }
        //    if (request.UrlReferrer != null)
        //    {
        //        httpReq.Referer = request.UrlReferrer.AbsoluteUri;
        //    }
        //    httpReq.UserAgent = request.UserAgent;
        //    httpReq.ContentLength = request.ContentLength;
        //    httpReq.ContentType = request.ContentType;
        //    httpReq.KeepAlive = !"close".Equals(request.Headers["Connection"], StringComparison.OrdinalIgnoreCase);//keep-alive
        //    httpReq.KeepAlive = false;
        //    httpReq.Connection = httpReq.Connection;
        //    DateTime ifModifiedSince;
        //    if (DateTime.TryParse(request.Headers["If-Modified-Since"], out ifModifiedSince))
        //    {
        //        httpReq.IfModifiedSince = ifModifiedSince;
        //    }
        //    string transferEncoding = request.Headers["Transfer-Encoding"];
        //    if (transferEncoding != null)
        //    {
        //        httpReq.SendChunked = true;
        //        httpReq.TransferEncoding = transferEncoding;
        //    }

        //    // Copy content (if content body is allowed)
        //    if (request.HttpMethod != WebRequestMethods.Http.Get && request.HttpMethod != WebRequestMethods.Http.Head && request.ContentLength > 0)
        //    {
        //        using (Stream httpReqStream = httpReq.GetRequestStream())
        //        {
        //            request.InputStream.CopyTo(httpReqStream, request.ContentLength);
        //            httpReqStream.Close();
        //        }
        //    }

        //    return httpReq;
        //}

        public static HttpWebRequest BuildHttpWebRequest(string url, NameValueCollection param, RequestMethod method, int timeoutInSecond, Encoding encoding, string userAgent, CookieContainer cookies, string referer, string acceptTypes, string host, NameValueCollection headers)
        {
            encoding = encoding ?? Encoding.UTF8;
            HttpWebRequest req = null;
            string fullurl = string.Empty;
            if (method != RequestMethod.POST && param != null && param.Count > 0)
                fullurl = WebUrlHelper.AppendNVP(url, param);
            else
                fullurl = url;

            req = WebRequest.Create(fullurl) as HttpWebRequest;
            if (fullurl.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; };
                req.ProtocolVersion = HttpVersion.Version10;
            }

            req.Method = method.ToString();
            if (timeoutInSecond > 99)
            {
                req.Timeout = timeoutInSecond;
            }
            else
            {
                req.Timeout = timeoutInSecond * 1000;
            }
            req.ReadWriteTimeout = req.Timeout;
            req.ServicePoint.Expect100Continue = false;
            if (!string.IsNullOrEmpty(host))
                req.Host = host;
            if (!string.IsNullOrEmpty(userAgent))
                req.UserAgent = userAgent;
            if (cookies != null)
                req.CookieContainer = cookies;
            if (!string.IsNullOrEmpty(referer))
                req.Referer = referer;
            if (!string.IsNullOrEmpty(acceptTypes))
                req.Accept = acceptTypes;
            if (!headers.IsNullOrEmpty())
                req.Headers.Add(headers);
            if (method == RequestMethod.POST || method == RequestMethod.PUT)
            {
                req.ContentType = "application/x-www-form-urlencoded";
                if (param != null && param.Count > 0)
                {
                    byte[] byteArray = encoding.GetBytes(param.GetNvpString(true));
                    req.ContentLength = byteArray.Length;
                    using (System.IO.Stream stream = req.GetRequestStream())
                    {
                        stream.Write(byteArray, 0, byteArray.Length);
                        stream.Close();
                    }
                }
            }

            return req;
        }
Example #21
0
        //done
        private bool ParseRequestLine()
        {
            //throw new NotImplementedException();
            requestLines = contentLines[0].Split(' ');
            if (requestLines.Length != 3)
            {
                return(false);
            }
            //Method
            if (requestLines[0] == RequestMethod.GET.ToString())
            {
                method = RequestMethod.GET;
            }
            else if (requestLines[0] == RequestMethod.HEAD.ToString())
            {
                method = RequestMethod.HEAD;
                Console.WriteLine(method.ToString());
            }
            else if (requestLines[0] == RequestMethod.POST.ToString())
            {
                method = RequestMethod.POST;
            }
            else
            {
                return(false);
            }
            //HTTP version
            //if (requestLines[2] != HTTPVersion.HTTP09.ToString() && requestLines[2] != HTTPVersion.HTTP10.ToString() && requestLines[2] != HTTPVersion.HTTP11.ToString())
            //    return false;
            if (requestLines[2] == "HTTP/0.9")
            {
                httpVersion = HTTPVersion.HTTP09;
            }
            else if (requestLines[2] == "HTTP/1.0")
            {
                httpVersion = HTTPVersion.HTTP10;
            }
            else if (requestLines[2] == "HTTP/1.1")
            {
                httpVersion = HTTPVersion.HTTP11;
            }
            else
            {
                return(false);
            }
            //URI
            if (ValidateIsURI(requestLines[1]))
            {
                relativeURI = requestLines[1];
            }
            else
            {
                return(false);
            }

            return(true);
        }
Example #22
0
        private HttpRequestMessage CreateRequest(string urlPath, RequestMethod method = RequestMethod.GET, object requestObject = null)
        {
            var request = new HttpRequestMessage(new HttpMethod(method.ToString()), urlPath);

            if (requestObject != null)
            {
                request.Content = new StringContent(JsonConvert.SerializeObject(requestObject, _jsonSettings), Encoding.UTF8, "application/json");
            }
            return(request);
        }
Example #23
0
        /// <summary>
        /// 建立HttpRequest实例
        /// </summary>
        /// <param name="method"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        private HttpWebRequest CreateWebRequest(RequestMethod method, string url)
        {
            var request = CreateRequest(method.ToString(), url, this.Timeout);

            foreach (var p in this.Headers.Items)
            {
                request.Headers.Add(p.Key, p.Value);
            }
            return(request);
        }
Example #24
0
        public void Enqueue(string url, string body, Action <int, string> callback, Plugin owner, RequestMethod method = RequestMethod.GET, Dictionary <string, string> headers = null, float timeout = 0f)
        {
            var request = new WebRequest(url, callback, owner)
            {
                Method = method.ToString(), RequestHeaders = headers, Timeout = timeout, Body = body
            };

            lock (syncroot) queue.Enqueue(request);
            workevent.Set();
        }
Example #25
0
        /// <summary>
        /// 签名方法
        /// https://www.qcloud.com/document/product/240/8329
        /// </summary>
        /// <param name="endpoint"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        private void GetSignature(string url,
                                  SortedDictionary <string, object> requestParams,
                                  RequestMethod requestMethod     = RequestMethod.GET,
                                  SignatureMethod signatureMethod = SignatureMethod.HmacSHA1)
        {
            /*
             * 1. 对参数排序
             * 2. 拼接请求字符串
             * 3. 拼接签名原文字符串
             * 4. 生成签名串
             * 5. 签名串编码(BASE64编码)
             */
            if (_patameters == null)
            {
                _patameters = new SortedDictionary <string, object>();
            }
            string tempStr = "";

            foreach (string key in requestParams.Keys)
            {
                if (key == "Signature")
                {
                    continue;
                }
                if (requestMethod == RequestMethod.POST && requestParams[key].ToString().Substring(0, 1).Equals("@"))
                {
                    continue;
                }
                tempStr += string.Format("{0}={1}&", key.Replace("_", "."), requestParams[key]);
            }

            tempStr = $"?{tempStr.TrimEnd('&')}";

            string retStr = $"{requestMethod.ToString()}{url}{_ServerUri}{tempStr}";


            if (signatureMethod == SignatureMethod.HmacSHA1)
            {
                using (var mac = new HMACSHA1(Encoding.UTF8.GetBytes(_SecretKey)))
                {
                    byte[] hash = mac.ComputeHash(Encoding.UTF8.GetBytes(retStr));
                    _patameters.Add("Signature", Convert.ToBase64String(hash));
                }
            }

            if (signatureMethod == SignatureMethod.HmacSHA256)
            {
                using (var mac = new HMACSHA256(Encoding.UTF8.GetBytes(_SecretKey)))
                {
                    byte[] hash = mac.ComputeHash(Encoding.UTF8.GetBytes(retStr));
                    _patameters.Add("Signature", Convert.ToBase64String(hash));
                    _patameters.Add("SignatureMethod", "HmacSHA256");
                }
            }
        }
Example #26
0
        /// <summary>
        /// Adds the correct headers and authorization.
        /// </summary>
        /// <param name="requestMethod">The request method we are doing</param>
        /// <param name="request">The request object</param>
        /// <returns>A RestRequest object with the correct authorization header</returns>
        private RestRequest CreateRequest(RequestMethod requestMethod, RestRequest request)
        {
            request.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0");
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Authorization",
                              $"Realo key=\"{ PublicKey }\", " +
                              $"signature=\"{ CreateSignature(requestMethod.ToString(), $"{Url}/{request.Resource}", request.Body != null ? request.Body.Value.ToString() : "") }\" " +
                              $"version=\"1.0\"");

            return(request);
        }
Example #27
0
        /// <inheritdoc />
        public async Task <string> RunRequest(Uri url, string body, IEnumerable <string> headers, RequestMethod requestMethod, CancellationToken cancellationToken)
        {
            if (url == null)
            {
                throw new ArgumentNullException(nameof(url));
            }
            if (body == null)
            {
                throw new ArgumentNullException(nameof(body));
            }
            if (headers == null)
            {
                throw new ArgumentNullException(nameof(headers));
            }

            logger.LogDebug("{0} to {1}", requestMethod, url);
            logger.LogTrace("Body: \"{0}\". Headers: {1}", body, String.Join(';', headers));

            var request = WebRequest.Create(url);

            request.Method = requestMethod.ToString();
            foreach (var I in headers)
            {
                request.Headers.Add(I);
            }

            using (var requestStream = await request.GetRequestStreamAsync().ConfigureAwait(false)) {
                var data = Encoding.UTF8.GetBytes(body);
                await requestStream.WriteAsync(data, 0, data.Length, cancellationToken).ConfigureAwait(false);
            }

            try
            {
                WebResponse response;
                using (cancellationToken.Register(() => request.Abort()))
                    response = await request.GetResponseAsync().ConfigureAwait(false);

                string result;
                using (var reader = new StreamReader(response.GetResponseStream()))
                    result = await reader.ReadToEndAsync().ConfigureAwait(false);

                logger.LogTrace("Request success.");
                return(result);
            }
            catch (Exception e)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    throw new OperationCanceledException("RunRequest() cancelled!", e, cancellationToken);
                }
                logger.LogWarning(e, "Request failed!");
                throw;
            }
        }
Example #28
0
        public static WebRequestProcess Create(string requestUriString, RequestMethod objRequestMethod = 0, int timeout = 0xea60)
        {
            WebRequestProcess process = new WebRequestProcess {
                WebRequest = System.Net.WebRequest.Create(requestUriString) as HttpWebRequest
            };

            process.WebRequest.Method    = objRequestMethod.ToString();
            process.WebRequest.Timeout   = timeout;
            process.WebRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36";
            return(process);
        }
Example #29
0
        /// <summary>
        /// 建立HttpRequest实例
        /// </summary>
        /// <param name="method"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        private HttpWebRequest CreateWebRequest(RequestMethod method, string url)
        {
            var request = CreateRequest(method.ToString(), url, this.Timeout);

            if (SetHeader != null)
            {
                SetHeader(request);
            }

            return(request);
        }
Example #30
0
        public static string SendRequest(Uri uri, RequestMethod method, string user_agent, string content_type, string post, params string[] additional_headers)
        {
            try
            {
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
                webRequest.Method = method.ToString();
                if (!string.IsNullOrEmpty(user_agent))
                {
                    webRequest.UserAgent = user_agent;
                }
                if (content_type != null)
                {
                    webRequest.ContentType = content_type;
                    using (var streamWriter = new StreamWriter(webRequest.GetRequestStream()))
                    {
                        if (post != "")
                        {
                            streamWriter.Write(post);
                            streamWriter.Flush();
                            streamWriter.Close();
                        }
                    }
                    webRequest.ContentLength = post.Length;
                }
                if (additional_headers.Length > 0 && additional_headers.Length % 2 == 0)
                {
                    for (int i = 0; i < additional_headers.Length; i += 2)
                    {
                        if (additional_headers[i].ToLower() == "content-type")
                        {
                            continue;
                        }
                        webRequest.Headers.Add(additional_headers[i], additional_headers[i + 1]);
                    }
                }

                var webResponse  = (HttpWebResponse)webRequest.GetResponse();
                var streamReader = new StreamReader(webResponse.GetResponseStream());
                var result       = streamReader.ReadToEnd();
                return(result);
            }
            catch (WebException ex)
            {
                if ((ex.Response as HttpWebResponse).StatusCode == HttpStatusCode.NotFound)
                {
                    throw new EntryPointNotFoundException((ex.Response as HttpWebResponse).ResponseUri.ToString());
                }
                else
                {
                    throw ex;
                }
            }
        }
Example #31
0
        public override XElement ToXml()
        {
            var result = CreateXml(enActionType.InvokeWebService, Source, Recordsets,
                                   new XAttribute("RequestUrl", RequestUrl ?? string.Empty),
                                   new XAttribute("RequestMethod", RequestMethod.ToString()),
                                   new XAttribute("JsonPath", JsonPath ?? string.Empty),
                                   new XElement("RequestHeaders", new XCData(RequestHeaders ?? string.Empty)),
                                   new XElement("RequestBody", new XCData(RequestBody ?? string.Empty))
                                   );

            return(result);
        }
Example #32
0
        public static HttpWebRequest CreateHttpRequest(Uri url, RequestMethod requestMethod)
        {
            var request = WebRequest.CreateHttp(url);

            request.Method      = requestMethod.ToString().ToUpperInvariant();
            request.ContentType = "application/json";
            request.Accept      = "application/json; charset=utf-8";

            TraceRequest(request);

            return(request);
        }
Example #33
0
 /// <summary>
 /// 网页请求
 /// </summary>
 /// <param name="postUrl">URL</param>
 /// <param name="requestMethod">请求方法</param>
 /// <param name="param">请求参数</param>
 /// <param name="encoding">编码</param>
 /// <param name="headers">头部</param>
 /// <returns></returns>
 public static string GetWebRequest(string postUrl, RequestMethod requestMethod = RequestMethod.Get ,string param = null, Encoding encoding = null, WebHeaderCollection headers = null)
 {
     postUrl = postUrl.Trim();
     if (postUrl.IndexOf("http://") != 0)
     {
         postUrl = "http://" + postUrl;
     }
     string ret = string.Empty;
     HttpWebResponse response;
     StackTrace st = new StackTrace(true);
     try
     {
         if (encoding == null)
         {
             encoding = Encoding.UTF8;
         }
         HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(new Uri(postUrl));
         if (headers != null) webRequest.Headers = headers;
         webRequest.Method = requestMethod.ToString();
         webRequest.ContentType = "application/x-www-form-urlencoded";
         webRequest.UserAgent = "User-Agent";
         webRequest.KeepAlive = true;
         if (param != null && requestMethod == RequestMethod.Post)
         {
             byte[] paramByte = encoding.GetBytes(param);
             webRequest.ContentLength = paramByte.Length;
             var webStream = webRequest.GetRequestStream();
             webStream.Write(paramByte, 0, paramByte.Length);
             webStream.Close();
         }
         response = (HttpWebResponse)webRequest.GetResponse();
         StreamReader sr = new StreamReader(response.GetResponseStream(), encoding);
         ret = sr.ReadToEnd();
         sr.Close();
         response.Close();
     }
     catch (Exception)
     {
         throw;
     }
     return ret;
 }
Example #34
0
        /// <summary>
        /// creates HttpWebRequest including IDataBase data, request params, query filter and granularity
        /// </summary>
        /// <param name="requestMethod">RequestMethod</param>
        /// <param name="model">Ataxo.SlimAPIClient.Entities.Constants.Model</param>
        /// <param name="requestParams">params od model usually used for updating</param>
        /// <param name="queryItems">filter params</param>
        /// <param name="granularity">Granularity</param>
        /// <returns></returns>
        protected HttpWebRequest CreateRequest(RequestMethod requestMethod, string model, string additional_concretization = null, IDictionary<string, object> requestParams = null, IEnumerable<QueryItem> queryItems = null, Granularity granularity = null)
        {
            string url = ConstrucUrl(PropertiesData, model, additional_concretization, queryItems, granularity);
              Uri uri = new Uri(url);

              HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
              request.ContentType = "application/json";
              request.Headers["Api-Token"] = PropertiesData.AccessToken;
              request.Method = requestMethod.ToString().ToUpper();

              return request;
        }
Example #35
0
		/// <summary>
		/// Wraps a web request into a convenient package.
		/// </summary>
		/// <param name="method">HTTP method of the request.</param>
		/// <param name="url">Full URL to the web resource.</param>
		/// <param name="postData">Data to post in query string format.</param>
		/// <returns>The web server response.</returns>
		private string MakeWebRequest (RequestMethod method,
		                               string url,
		                               List<IQueryParameter<string>> parameters,
		                               string postData)
		{
			var responseData = string.Empty;

			ServicePointManager.CertificatePolicy = new CertificateManager ();

			// TODO: Set UserAgent, Timeout, KeepAlive, Proxy?
			HttpWebRequest webRequest = ProxiedWebRequest.Create (url);
			webRequest.Method = method.ToString ();
			webRequest.ServicePoint.Expect100Continue = false;

			var headerParams =
				parameters.Implode (",", q => string.Format ("{0}=\"{1}\"", q.Name, q.Value));
			if (Debugging)
				Logger.Debug ("Generated auth header params string: " + headerParams);
			webRequest.Headers.Add ("Authorization",
			                        String.Format ("OAuth realm=\"{0}\",{1}",
			                                       Realm, headerParams));
            if (postData == null) {
                postData = string.Empty;
            }

			if (method == RequestMethod.PUT ||
			     method == RequestMethod.POST) {
				webRequest.ContentType = "application/json";
				// TODO: Error handling?
				using (var requestWriter = new StreamWriter (webRequest.GetRequestStream ()))
					requestWriter.Write (postData);
			}

			try {
				using (var responseReader = new StreamReader (webRequest.GetResponse ().GetResponseStream ())) {
			      		responseData = responseReader.ReadToEnd ();
				}
			} catch (Exception e) {
				Logger.Error ("Caught exception. Message: {0}", e.Message);
				Logger.Error ("Stack trace for previous exception: {0}", e.StackTrace);
				Logger.Error ("Rest of stack trace for above exception: {0}", System.Environment.StackTrace);
				throw;
			}

			if (Debugging)
				Logger.Debug ("Made web request, got response: {0}", responseData);

			return responseData;
		}
        private JObject Request(string resourceUri, RequestMethod method, JObject data, NameValueCollection headers)
        {
            var resourcePath = string.Format("{0}/{1}", ApiBase, resourceUri.Trim('/')).Trim('?');

            if (headers != null)            
                Headers.AllKeys.ToList().ForEach(key => headers.Add(key, Headers[key]));
            
            else            
                headers = Headers;
           
            // Send request

            if (Logger.IsInfoEnabled)            
                Logger.Info(string.Format("{0} {1}", method.ToString(), resourcePath));
            
            var requestHeaders = new WebHeaderCollection();
            requestHeaders.Add(headers);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resourcePath);
            request.Method = method.ToString();
            request.Headers = requestHeaders;

            if (method != RequestMethod.GET)
            {
                var stringData = "{}";
                if (data != null)                
                    stringData = JsonConvert.SerializeObject(data);                

                request.ContentType = "application/json";
                request.ContentLength = stringData.Length;
                try
                {                
                    using (Stream webStream = request.GetRequestStream())
                    {
                        using (StreamWriter requestWriter = new StreamWriter(webStream))
                        {
                            requestWriter.Write(stringData);
                        }
                    }
                }
                catch (Exception)
                {
                }
            }

            var content = "";
            var resp = new NameValueCollection();

            try
            {
                var webResponse = (HttpWebResponse)request.GetResponse();

                resp["status"] = ((int)webResponse.StatusCode).ToString();
                webResponse.Headers.AllKeys.ToList().ForEach(key => resp.Add(key, webResponse.Headers[key]));

                using (Stream webStream = webResponse.GetResponseStream())
                {
                    if (webStream != null)
                    {
                        using (StreamReader responseReader = new StreamReader(webStream))
                        {
                            content = responseReader.ReadToEnd();
                        }
                    }
                }
            }
            catch (WebException e)
            {
                try
                {
                    var webResponse = (HttpWebResponse)e.Response;
                    resp["status"] = ((int)webResponse.StatusCode).ToString();
                    e.Response.Headers.AllKeys.ToList().ForEach(key => resp.Add(key, e.Response.Headers[key]));
                    using (Stream webStream = e.Response.GetResponseStream())
                    {
                        if (webStream != null)
                        {
                            using (StreamReader responseReader = new StreamReader(webStream))
                            {
                                content = responseReader.ReadToEnd();
                            }
                        }
                    }
                }
                catch (Exception err)
                {
                    if (Logger.IsErrorEnabled)
                        Logger.Error(err.Message);
                    return GetResponse("0", err.Message, null, null);
                }
            }
            catch (Exception err)
            {
                if (Logger.IsErrorEnabled)
                    Logger.Error(err.Message);
                return GetResponse("0", err.Message, null, null);
            }

            JObject jsonContent = null;
            try
            {
                jsonContent = JObject.Parse(content);
            }
            catch (Exception)
            {
                jsonContent = JObject.Parse("{}");
            }

            // Log request

            if (Logger.IsDebugEnabled)
            {
                var logData = new JObject
                {
                    {"resource_path", resourcePath},
                    {"method", method.ToString()},
                    {"request_headers", JObject.FromObject(headers.AllKeys.ToDictionary(k => k, k => headers[k]))},
                    {"request_data", data},                
                    {"response_headers", JObject.FromObject(resp.AllKeys.ToDictionary(k => k, k => resp[k]))},
                    {"response_body", jsonContent},
                };
                Logger.Debug(JsonConvert.SerializeObject(logData, Formatting.Indented));
            }

            // Prepare result

            var statusCode = resp["status"];
            var statusReason = "";
            if (new string[] { "200", "201", "204" }.Contains(statusCode))            
                statusReason = "success";            
            else
            {
                var reason = resp["ErrorMessage"];
                if (reason != null)                
                    statusReason = string.Format("error: {0}", reason);
                else                
                    statusReason = "error";
            }

            return GetResponse(statusCode, statusReason, jsonContent, resp);
        }
        /// <summary>
        /// Web Request Wrapper
        /// </summary>
        /// <param name="method">Http Method</param>
        /// <param name="url">Full url to the web resource</param>
        /// <param name="postData">Data to post in querystring format</param>
        /// <returns>The web server response.</returns>
        public string WebRequest(RequestMethod method, string url, string postData)
        {
            string responseData = "";

            HttpWebRequest webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;

            if (webRequest != null)
            {
                webRequest.Method = method.ToString();
                webRequest.ServicePoint.Expect100Continue = false;
                //webRequest.UserAgent  = "Identify your application please.";
                //webRequest.Timeout = 20000;

                if (method == RequestMethod.POST || method == RequestMethod.DELETE)
                {
                    webRequest.ContentType = "application/x-www-form-urlencoded";

                    //POST the data.
                    using (StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream()))
                    {
                        try
                        {
                            requestWriter.Write(postData);
                        }
                        finally
                        {
                            requestWriter.Close();
                        }
                    }
                }

                responseData = WebResponseGet(webRequest);
            }
            webRequest = null;

            return responseData;
        }
Example #38
0
 /// <summary>
 /// Get Authentication header text
 /// </summary>
 protected string GetHeader(string uri, RequestMethod method, IEnumerable<KeyValuePair<string, string>> param, string pin = null, bool gettingRequestToken = false)
 {
     var oap = GetOAuthParams(
         ConsumerKey, Token,
         GetTimestamp(), GetNonce(),
         SignatureMethod, pin, gettingRequestToken);
     var sig = GetSignature(
         new Uri(uri), ConsumerSecret, Secret,
         JoinParamAsUrl(param == null ? oap : oap.Concat(param)),
         SignatureMethod, method.ToString());
     return JoinParamAsHeader(
         oap.Concat(new[] { new KeyValuePair<string, string>(SignatureKey, sig) }).ToArray());
 }
Example #39
0
        /// <summary>
        /// RequestStreamAPI implementation
        /// </summary>
        /// <param name="uri">full uri</param>
        /// <param name="method">using method for HTTP negotiation</param>
        /// <param name="param">parameters</param>
        /// <returns>Callback stream</returns>
        public override sealed Stream RequestStreamingAPI(string uri, RequestMethod method, IEnumerable<KeyValuePair<string, string>> param, out HttpWebRequest request)
        {
            if (String.IsNullOrEmpty(uri))
                throw new ArgumentNullException(uri);
            else if (uri.Length < 5)
                throw new ArgumentException("uri is too short.");
            string target = uri;

            if (String.IsNullOrEmpty(Token) || String.IsNullOrEmpty(Secret))
            {
                throw new WebException("OAuth Not Validated", WebExceptionStatus.ProtocolError);
            }

            var reg = GetHeader(target, method, param);
            try
            {
                var ps = JoinParamAsUrl(param);
                System.Diagnostics.Debug.WriteLine("streaming params:" + ps);
                byte[] body = null;
                if (!String.IsNullOrWhiteSpace(ps))
                {
                    if (method == RequestMethod.GET)
                        target += "?" + ps;
                    if (method == RequestMethod.POST)
                        body = Encoding.ASCII.GetBytes(ps);
                }
                request = Http.CreateRequest(new Uri(target), method.ToString(), contentType: "application/x-www-form-urlencoded");
                request.Headers.Add("Authorization", "OAuth " + reg);
                request.Timeout = 8000;
                request.AutomaticDecompression = DecompressionMethods.None; // due to delaying streaming receiving.

                var ret = Http.WebConnect<Stream>(req: request, responseconv: Http.ResponseConverters.GetStream, senddata: body);
                if (ret.Succeeded)
                {
                    return ret.Data;
                }
                else
                {
                    if (ret.Data != null)
                        ret.Data.Close();
                    if (ret.ThrownException != null)
                        throw ret.ThrownException;
                    else
                        throw new WebException();
                }
            }
            catch (WebException)
            {
                throw;
            }
            catch (IOException)
            {
                throw;
            }
        }
Example #40
0
        /// <summary>
        /// RequestAPI implementation
        /// </summary>
        /// <param name="uri">full uri</param>
        /// <param name="method">using method for HTTP negotiation</param>
        /// <param name="param">additional parameters</param>
        /// <param name="request">used request</param>
        /// <returns>XML documents</returns>
        public override sealed XDocument RequestAPI(string uri, RequestMethod method, IEnumerable<KeyValuePair<string, string>> param, out HttpWebRequest request)
        {
            // validate arguments
            if (String.IsNullOrEmpty(uri))
                throw new ArgumentNullException(uri);
            else if (uri.Length < 5)
                throw new ArgumentException("uri is too short.");
            string target = uri;

            // detection return type of api
            var docType = DocumentTypes.Invalid;

            if (target.EndsWith("xml"))
                docType = DocumentTypes.Xml;
            else if (target.EndsWith("json"))
                docType = DocumentTypes.Json;
            else
                throw new ArgumentException("format can't identify. uriPartial is must ends with .xml or .json.");

            // pre-validation authentication
            if (String.IsNullOrEmpty(Token) || String.IsNullOrEmpty(Secret))
            {
                throw new WebException("OAuth Not Validated", WebExceptionStatus.ProtocolError);
            }
            var reg = GetHeader(target, method, param);
            try
            {
                var ps = JoinParamAsUrl(param);
                byte[] body = null;
                if (!String.IsNullOrWhiteSpace(ps))
                {
                    if (method == RequestMethod.GET)
                        target += "?" + ps;
                    if (method == RequestMethod.POST)
                        body = Encoding.ASCII.GetBytes(ps);
                }
                request = Http.CreateRequest(new Uri(target), method.ToString(), contentType: "application/x-www-form-urlencoded");
                request.Headers.Add("Authorization", "OAuth " + reg);
                var ret = Http.WebConnect<XDocument>(request,
                    responseconv: new Http.ResponseConverter<XDocument>((res) =>
                    {
                        switch (docType)
                        {
                            case DocumentTypes.Xml:
                                return XDocumentGenerator(res);
                            case DocumentTypes.Json:
                                return XDocumentGenerator(res, (s) => JsonReaderWriterFactory.CreateJsonReader(s, XmlDictionaryReaderQuotas.Max));
                            default:
                                throw new NotSupportedException("Invalid format.");
                        }
                    }), senddata: body);
                if (ret.Succeeded && ret.Data != null)
                {
                    return ret.Data;
                }
                else
                {
                    if (ret.ThrownException != null)
                        throw ret.ThrownException;
                    else
                        throw new WebException();
                }
            }
            catch (WebException)
            {
                throw;
            }
            catch (XmlException)
            {
                throw;
            }
            catch (IOException)
            {
                throw;
            }
        }
Example #41
0
		/// <summary>
		/// Generate the signature base that is used to produce the signature
		/// </summary>
		/// <param name="url">The full URL that needs to be signed including its non OAuth URL parameters.</param>
		/// <param name="consumerKey">The consumer key.</param>
		/// <param name="token">The token, if available. If not available pass null or an empty string.</param>
		/// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string.</param>
		/// <param name="verifier">The callback verifier, if available. If not available pass null or an empty string.</param>
		/// <param name="httpMethod">The HTTP method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param>
		/// <param name="signatureType">The signature type. To use the default values use <see cref="SignatureType">SignatureType</see>.</param>
		/// <returns>The signature base.</returns>
		private string GenerateSignatureBase (Uri url, string consumerKey, string token, string tokenSecret, string verifier,
						      RequestMethod method, TimeSpan timeStamp, string nonce, SignatureType signatureType, string callbackUrl,
						      out string normalizedUrl,
			out List<IQueryParameter<string>> parameters)
		{
			log.LogDebug ("Generating signature base for OAuth request.");

			token = token ?? string.Empty;
			tokenSecret = tokenSecret ?? string.Empty;
			verifier = verifier ?? String.Empty;

			if (consumerKey == null) throw new ArgumentNullException ("consumerKey");

			log.LogDebug ("URL: {0}", url.Query);

			var signatureString = string.Empty;

			switch (signatureType) {
				case SignatureType.HMACSHA1:
					signatureString = "HMAC-SHA1";
					break;
				case SignatureType.RSASHA1:
					signatureString = "RSA-SHA1";
					break;
				case SignatureType.PLAINTEXT:
					signatureString = SignatureType.PLAINTEXT.ToString ();
					break;
			}

			parameters = GetQueryParameters (url.Query).Concat (new List<IQueryParameter<string>> {
				new QueryParameter<string> (OAuthVersionKey, OAuthVersion, s => string.IsNullOrEmpty (s)),
				new QueryParameter<string> (OAuthTimestampKey, ((long)timeStamp.TotalSeconds).ToString (), s => string.IsNullOrEmpty (s)),
				new QueryParameter<string> (OAuthSignatureMethodKey, signatureString, s => string.IsNullOrEmpty (s)),
				new QueryParameter<string> (OAuthNonceKey, nonce, s => string.IsNullOrEmpty (s)),
				new QueryParameter<string> (OAuthConsumerKeyKey, consumerKey, s => string.IsNullOrEmpty (s))
			}).ToList ();

			if (!string.IsNullOrEmpty (token)) parameters.Add (new QueryParameter<string> (OAuthTokenKey, token, s => string.IsNullOrEmpty (s)));
			if (!string.IsNullOrEmpty (verifier)) parameters.Add (new QueryParameter<string> (OAuthVerifierKey, verifier, s => string.IsNullOrEmpty (s)));
			if (!string.IsNullOrEmpty (callbackUrl)) parameters.Add (new QueryParameter<string> (OAuthCallbackKey, UrlEncode (callbackUrl), s => string.IsNullOrEmpty (s)));

			log.LogDebug ("Normalizing URL for signature.");

			normalizedUrl = string.Format ("{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;

			log.LogDebug ("Generated normalized URL: {0}", normalizedUrl);
			log.LogDebug ("Normalizing request parameters.");

			parameters.Sort ();
			string normalizedRequestParameters = parameters.NormalizeRequestParameters ();

			log.LogDebug ("Normalized request parameters {0}.", normalizedRequestParameters);
			log.LogDebug ("Generating signature base from normalized URL and request parameters.");

			var signatureBase = new StringBuilder ();
			signatureBase.AppendFormat("{0}&", method.ToString ());
			signatureBase.AppendFormat("{0}&", UrlEncode (normalizedUrl));
			signatureBase.AppendFormat("{0}", UrlEncode (normalizedRequestParameters));

			log.LogDebug ("Signature base: {0}", signatureBase.ToString ());

			return signatureBase.ToString ();
		}
Example #42
0
 private HttpWebRequest PrepareRequest(Uri uri, RequestMethod method, string contentType)
 {
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
     request.AllowAutoRedirect = false;
     request.Method = method.ToString().ToUpper();
     if (method == RequestMethod.Post)
     {
         request.ContentType = contentType;
     }
     if (!_isRunningOnMono)
     {
         request.AutomaticDecompression = DecompressionMethods.GZip |
             DecompressionMethods.Deflate;
     }
     else
     {
         request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
     }
     request.ServicePoint.Expect100Continue = false;
     request.Expect = "";
     request.UserAgent = _userAgent;
     request.CookieContainer = new CookieContainer();
     if (_cookies != null && _cookies.Count > 0)
     {
         request.CookieContainer = _cookies;
     }
     return request;
 }
Example #43
0
        private HttpWebResponse GetResponseFromWattRequest(Uri requestUrl, RequestMethod method, string postData = "")
        {
            try
            {
                var httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUrl);

                httpWebRequest.Credentials = CredentialCache.DefaultCredentials;
                httpWebRequest.CookieContainer = _cookieJar;
                httpWebRequest.UserAgent = "CSharp HTTP Sample";
                httpWebRequest.KeepAlive = true;
                httpWebRequest.Headers.Set("Pragma", "no-cache");
                httpWebRequest.Timeout = 300000;
                httpWebRequest.Method = method.ToString();
                if (method == RequestMethod.Post)
                {
                    httpWebRequest.ContentType = "application/x-www-form-urlencoded";
                    byte[] bytes = Encoding.ASCII.GetBytes(postData);
                    httpWebRequest.ContentLength = bytes.Length;
                    Stream requestStream = httpWebRequest.GetRequestStream();
                    requestStream.Write(bytes, 0, bytes.Length);
                    requestStream.Close();
                }
                return (HttpWebResponse)httpWebRequest.GetResponse();
            }
            catch
            {
                return null;
            }
        }
Example #44
0
 protected Method ConvertRequestMethod(RequestMethod method)
 {
     if (method == RequestMethod.Get)
         return Method.GET;
     else if (method == RequestMethod.Post)
         return Method.POST;
     else
         throw new NotSupportedException(
             string.Format("The request method of {0} is not supported", method.ToString()));
 }
Example #45
0
                /// <summary>
                /// <value>url</value>�ɑ΂���<value>method</value>�Ń��N�G�X�g��s���܂��B
                /// </summary>
                /// <param name="url">URL</param>
                /// <param name="method">���N�G�X�g���\�b�h(GET/POST)</param>
                /// <param name="param">���N�G�X�g���̃p�����[�^(�Ȃ��ꍇ��null)</param>
                /// <param name="timeout">�^�C���A�E�g��w��</param>
                /// <param name="referer">���t�@�� �w�肵�Ȃ��ꍇ��null</param>
                /// <returns>WebRequest</returns>
                protected internal void doRequest(string url, RequestMethod method, string param, int timeout, string referer)
                {
                    try
                    {
                        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
                        req.Method = method.ToString();
                        req.UserAgent = LoginController.__USER_AGENT__;
                        req.Headers.Add(HttpRequestHeader.AcceptLanguage, "ja");
                        req.Headers.Add(HttpRequestHeader.AcceptEncoding, "*/*");
                        req.KeepAlive = true;
                        req.AllowAutoRedirect = true;
                        if (referer != null && referer.Length > 0)
                        {
                            req.Referer = referer;
                        }
                        req.Timeout = timeout;
                        if (param != null && param.Length > 0)
                        {
                            data = System.Text.Encoding.ASCII.GetBytes(param);
                            req.ContentLength = data.Length;
                        }
                        if (method == RequestMethod.POST)
                        {
                            req.ContentType = "application/x-www-form-urlencoded";
                        }
                        req.KeepAlive = true;
                        //req.AllowAutoRedirect = true;
                        req.AllowAutoRedirect = false;
                        if (this.cc != null && this.cc.Count > 0)
                        {
                            //req.CookieContainer = new CookieContainer();
                            //req.CookieContainer.Add(this.cc.GetCookies(req.RequestUri));
                            req.CookieContainer = this.cc;
                        }
                        else
                        {
                            this.cc = new CookieContainer();
                            req.CookieContainer = this.cc;
                        }

                        SimpleLogger.WriteLine("[ Request ] ----------------------------------------");
                        SimpleLogger.WriteLine("URL: " + url);
                        SimpleLogger.WriteLine("Method: " + req.Method);
                        if (param != null && param.Length > 0)
                        {
                            SimpleLogger.WriteLine("Query: " + param);
                        }
                        SimpleLogger.WriteLine(req.Headers.ToString().Replace("\n\r", Environment.NewLine));
                        SimpleLogger.WriteLine("----------------------------------------------------");

                        if (method == RequestMethod.POST)
                        {
                            // �|�X�g�E�f�[�^�̏�������
                            Stream reqStream = req.GetRequestStream();
                            reqStream.Write(data, 0, data.Length);
                            reqStream.Close();
                        }

                        this.webReq = req;
                    }
                    catch (System.NotSupportedException nse)
                    {
                        throw nse;
                    }
                    catch (System.ArgumentException ae)
                    {
                        throw ae;
                    }
                    catch (System.Security.SecurityException se)
                    {
                        throw se;
                    }
                }
        /// <summary>
        /// Submit a web request using oAuth.
        /// </summary>
        /// <param name="method">GET or POST</param>
        /// <param name="url">The full url, including the querystring.</param>
        /// <param name="postData">Data to post (querystring format)</param>
        /// <returns>The web server response.</returns>
        public string OAuthWebRequest(RequestMethod method, string url, string postData)
        {
            string outUrl = "";
            string querystring = "";
            string ret = "";

            //Setup postData for signing.
            //Add the postData to the querystring.
            if (method == RequestMethod.POST || method == RequestMethod.DELETE)
            {
                if (postData.Length > 0)
                {
                    //Decode the parameters and re-encode using the oAuth UrlEncode method.
                    NameValueCollection qs = HttpUtility.ParseQueryString(postData);
                    postData = "";
                    foreach (string key in qs.AllKeys)
                    {
                        if (postData.Length > 0)
                        {
                            postData += "&";
                        }
                        qs[key] = HttpUtility.UrlDecode(qs[key]);
                        qs[key] = UrlEncode(qs[key]);
                        postData += key + "=" + qs[key];
                    }
                    if (url.IndexOf("?", StringComparison.Ordinal) > 0)
                    {
                        url += "&";
                    }
                    else
                    {
                        url += "?";
                    }
                    url += postData;
                }
            }

            var uri = new Uri(url);

            string nonce = GenerateNonce();
            string timeStamp = GenerateTimeStamp();

            //Generate Signature
            string sig = GenerateSignature(uri,
                                           ConsumerKey,
                                           ConsumerSecret,
                                           Token,
                                           TokenSecret,
                                           CallBackUrl,
                                           OAuthVerifier,
                                           method.ToString(),
                                           timeStamp,
                                           nonce,
                                           out outUrl,
                                           out querystring);

            querystring += "&oauth_signature=" + UrlEncode(sig);

            //Convert the querystring to postData
            if (method == RequestMethod.POST || method == RequestMethod.DELETE)
            {
                postData = querystring;
                querystring = "";
            }

            if (querystring.Length > 0)
            {
                outUrl += "?";
            }

            ret = WebRequest(method, outUrl + querystring, postData);

            return ret;
        }
Example #47
0
 private string CreateUrl(string uri, RequestMethod method, IEnumerable<KeyValuePair<string, string>> param, string pin)
 {
     StringBuilder sb = new StringBuilder();
     param = AddOAuthParams(
         param,
         ConsumerKey, Token,
         GetTimestamp(), GetNonce(),
         SignatureType, pin);
     string strp = JoinParam(param);
     string sig = GetSignature(
         new Uri(uri),
         ConsumerSecret, Secret,
         strp, SignatureType, method.ToString());
     List<KeyValuePair<string, string>> np = new List<KeyValuePair<string, string>>();
     if (param != null)
         np.AddRange(param);
     np.Add(new KeyValuePair<string, string>(SignatureKey, sig));
     return uri + "?" + JoinParam(np);
 }
Example #48
0
 internal AsyncState(byte[] data, Action<Stream> dele, string url, RequestMethod method, CookieContainer cc)
 {
     this.data = data;
     this.dele = dele;
     this.url = url;
     this.method = method;
     this.cc = cc;
     this.r = HttpWebRequest.Create(url) as HttpWebRequest;
     this.r.Method = method.ToString().ToUpper();
     this.r.CookieContainer = cc;
     this.r.ContentType = "application/x-www-form-urlencoded";
 }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="requestMethod"></param>
        /// <param name="url"></param>
        /// <param name="authorisationToken"></param>
        /// <param name="navigationPage"></param>
        /// <param name="navigationPageSize"></param>
        /// <returns></returns>
        private static HttpWebRequest CreateHttpWebRequest(RequestMethod requestMethod, string url, string authorisationToken, int? navigationPage = null, int? navigationPageSize = null, string methodOverride = null)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "application/xml";
            request.Method = requestMethod.ToString();
            request.KeepAlive = false;
            request.Accept = "application/xml";
            request.Headers.Add("Authorization", authorisationToken);

            if (navigationPage.HasValue)
            {
                request.Headers.Add("navigationPage", navigationPage.Value.ToString());
            }

            if (navigationPageSize.HasValue)
            {
                request.Headers.Add("navigationPageSize", navigationPageSize.Value.ToString());
            }

            if (!String.IsNullOrWhiteSpace(methodOverride))
            {
                request.Headers.Add("X-HTTP-Method-Override", methodOverride.Trim());
            }

            return request;
        }