Ejemplo n.º 1
0
        private async Task<object> CallAsync(HttpMethods method, string path, object callParams)
        {
            string url = String.Format("https://{0}.myshopify.com{1}", State.ShopName, path);
            var req = new HttpClient();
            req.DefaultRequestHeaders.Add("X-Shopify-Access-Token", this.State.AccessToken);
            
            HttpResponseMessage response = null;
            if (method == HttpMethods.GET || method == HttpMethods.DELETE)
            {
                // if no translator assume data is a query string
                url = String.Format("{0}?{1}", url, callParams != null ? callParams.ToString() : null);

                if (method == HttpMethods.GET)
                {
                    response = await req.GetAsync(url);
                }
                else
                {
                    response = await req.DeleteAsync(url);
                }
            }
            else if (method == HttpMethods.POST || method == HttpMethods.PUT)
            {
                string requestBody;
                // put params into post body
                if (Translator == null)
                {
                    //assume it's a string
                    requestBody = callParams.ToString();
                }
                else
                {
                    requestBody = Translator.Encode(callParams);
                }


                if (method == HttpMethods.POST)
                {
                    response = await req.PostAsync(url, new StringContent(requestBody));
                }
                else
                {
                    response = await req.PutAsync(url, new StringContent(requestBody));
                }
            }

            if (response != null && response.IsSuccessStatusCode)
            {
                //response.Content.Headers.Add("Content-Type", GetRequestContentType());
                var result = await response.Content.ReadAsStringAsync();

                if (Translator != null)
                    return Translator.Decode(result);

                return result;
            }

            return null;
        }
 /// <summary>
 /// Make an HTTP Request to the 500px API
 /// </summary>
 /// <param name="method">method to be used in the request</param>
 /// <param name="path">the path that should be requested</param>
 /// <param name="callParams">any parameters needed or expected by the API</param>
 /// <seealso cref="http://developers.500px.com/"/>
 /// <returns>the server response</returns>
 public IAsyncOperation<object> Call(HttpMethods method, string path, object callParams)
 {
     return (CallAsync(method, path, callParams)).AsAsyncOperation<object>();
 }
 /// <summary>
 /// Make an HTTP Request to the 500px API
 /// </summary>
 /// <param name="method">method to be used in the request</param>
 /// <param name="path">the path that should be requested</param>
 /// <seealso cref="http://developers.500px.com/"/>
 /// <returns>the server response</returns>
 public IAsyncOperation<object> Call(HttpMethods method, string path)
 {
     return Call(method, path, null);
 }
Ejemplo n.º 4
0
        private static RequestResult _Request(HttpMethods method, string url, byte[] data, HttpRequestDataFormat dataFormat, Dictionary<string, string> headers, IEnumerable<Cookie> Cookies, ICredentials Credentials, Action<RequestResult> callback, ProgressReportDelegate progressReportCallback)
        {
            //enable protocols
#if NETFX
#if __MonoCS__
            try{ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;}catch{}
#warning WARNING the system is not secure when using only TLS1 !!!! you must use visual studio.
#elif UNIVERSAL
            try{ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;} catch{}
#endif
#endif

            //add request cookies
            var cookieContainer = new CookieContainer();
            if (Cookies != null)
                foreach (var entry in Cookies)
#if NETFX
                    cookieContainer.Add(entry);
#elif UNIVERSAL
                    cookieContainer.Add(new Uri(url), entry);
#endif

            //creat request
            HttpWebRequest webRequest;
            try { webRequest = (HttpWebRequest)WebRequest.Create(url); }
            catch (Exception ex)
            {
                DebugEx.TraceError(ex, "Http request failed");
                if (callback != null)
                    callback(default(RequestResult));
                return default(RequestResult);
            }

            //setup request
            webRequest.CookieContainer = cookieContainer;
            if (Credentials == null)
                webRequest.UseDefaultCredentials = true;
            else
                webRequest.Credentials = Credentials;
#if NETFX
            webRequest.PreAuthenticate = true;
            webRequest.ServicePoint.Expect100Continue = false;

            //collect certificates
            /*
            if (!EnvironmentEx.IsRunningOnMono) 
                webRequest.ClientCertificates = Tools.Certificates.CollectCertificates();
            */

            webRequest.AllowAutoRedirect = true;
            webRequest.MaximumAutomaticRedirections = 10;
            webRequest.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip | DecompressionMethods.None;
            webRequest.UserAgent = UserAgent;
#elif UNIVERSAL
            webRequest.Headers[HttpRequestHeader.UserAgent] = UserAgent;
#endif
            webRequest.Accept = "*/*";

            try
            {
#if NETFX
                //build headers
                if (headers != null)
                    foreach (var header in headers)
                        webRequest.Headers.Add(header.Key, header.Value);
#endif
                //setup method
                switch (method)
                {
                    case HttpMethods.Get:
                        webRequest.Method = "GET";
                        break;
                    case HttpMethods.Post:
                        webRequest.Method = "POST";
                        break;
                    case HttpMethods.Put:
                        webRequest.Method = "PUT";
                        break;
                    default:
                        DebugEx.Assert("Invalid Method");
                        throw new NotImplementedException("Invalid Method");
                }

                //build request
                if (method == HttpMethods.Get)
                {
#if NETFX
                    webRequest.ContentLength = 0;
                    webRequest.ContentType = webRequest.MediaType = "application/x-www-form-urlencoded";
#endif
                }
                else
                {
                    string contentType = null;
                    switch (dataFormat)
                    {
                        case HttpRequestDataFormat.Json:
                            contentType = "application/json";
                            break;
                        case HttpRequestDataFormat.Xml:
                            contentType = "application/xhtml+xml";
                            break;
                        case HttpRequestDataFormat.FormData:
                            contentType = "application/x-www-form-urlencoded";
                            break;
                        case HttpRequestDataFormat.Text:
                            contentType = "mime/text";
                            break;
                        case HttpRequestDataFormat.Soap:
                            if (headers.ContainsKey("SoapContent-Type"))
                            {
                                contentType = headers["SoapContent-Type"];
                                webRequest.Headers.Remove("SoapContent-Type");
                            }
                            break;
                        case HttpRequestDataFormat.Binary:
                            contentType = "application/octet-stream";
                            break;
                    }
                    webRequest.ContentType = contentType;
#if NETFX
                    webRequest.MediaType = contentType;
#endif

                    //write body data
                    var body_data = data ?? new byte[0];
#if NETFX
                    webRequest.ContentLength = body_data.Length;
                    using (var stream = webRequest.GetRequestStream())
                        stream.Write(body_data, 0, body_data.Length);
#elif UNIVERSAL
                    using (var stream = webRequest.GetRequestStreamAsync().GetResults())
                        stream.Write(body_data, 0, body_data.Length);
#endif
                }

                //get response
                HttpWebResponse response = null;
                Stream respstream = null;
                try
                {
#if NETFX
                    var _response = webRequest.GetResponse();
#elif UNIVERSAL
                    var _response = webRequest.GetResponseAsync().GetResults();
#endif
                    response = (HttpWebResponse)_response;
                    respstream = response.GetResponseStream();
                }
                catch (WebException ex)
                {
                    response = ex.Response as HttpWebResponse;
                    if (response != null && response.StatusCode == HttpStatusCode.RedirectMethod)
                        DebugEx.TraceLog("Redirected from url " + url + " to url " + response.ResponseUri);
                    else if (response != null && response.StatusCode == HttpStatusCode.NotFound)
                        DebugEx.TraceLog("404 - Not Found. Url=" + url);
                    else
                        DebugEx.TraceError(ex, "Unhandled exception during webRequest.GetResponse() for url " + url);
                    //try get response stream
                    try
                    {
                        if (response != null)
                            respstream = response.GetResponseStream();
                    }
                    catch (WebException ex2)
                    {
                        DebugEx.TraceError(ex2, "Unhandled exception during redirect webRequest.GetResponseStream() for url " + url);
                    }
                }


                //Read results and execute callback                
                if (response != null)
                {
                    //find encoding
                    var encoding = response.Headers["content-encoding"];
                    var contentType = response.Headers["content-type"];
                    var contentTypeEntries = contentType?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    if (contentTypeEntries != null)
                        for (int n = 0; n > contentTypeEntries.Length; n++)
                            contentTypeEntries[n] = contentTypeEntries[n].Trim();
                    //find charset
                    string charset = "";
                    if (contentTypeEntries != null && contentType != null && contentType.Contains("charset="))
                        try
                        {
                            var entry = contentTypeEntries.FirstOrDefault(e => e.ToLowerInvariant().StartsWith("charset="));
                            if (!string.IsNullOrWhiteSpace(entry))
                                charset = entry.Split(new[] { "=" }, StringSplitOptions.RemoveEmptyEntries)[1].ToLowerInvariant();
                        }
                        catch { charset = "utf-8"; }

                    //consume stream
                    byte[] bytes = null;
                    if (respstream != null)
                        try
                        {
                            using (var memStream = new MemoryStream())
                            {
                                if (progressReportCallback == null)
                                {
                                    //unzip or just copy to memstream
                                    if (encoding != null && encoding.ToLowerInvariant() == "gzip")
                                        using (var defStream = new GZipStream(respstream, CompressionMode.Decompress))
                                            defStream.CopyTo(memStream);
                                    else
                                        respstream.CopyTo(memStream);
                                }
                                else
                                {
                                    //unzip or just copy to memstream
                                    if (encoding != null && encoding.ToLowerInvariant() == "gzip")
                                        using (var defStream = new GZipStream(respstream, CompressionMode.Decompress))
                                            StreamCopy(defStream, memStream, progressReportCallback, response.ContentLength);
                                    else
                                        StreamCopy(respstream, memStream, progressReportCallback, response.ContentLength);
                                }

                                //get bytes
                                bytes = memStream.ToArray();
                            }
                        }
                        catch (Exception ex) { DebugEx.Assert(ex, "Unhandled exception while reading response stream"); }

                    //build result
                    var result = new RequestResult()
                    {
                        IsValid = true,
                        ResponseUri = response.ResponseUri,
                        ResponseBodyBinary = bytes,
                        ContentTypeEntries = contentTypeEntries,
                        Charset = charset,
                        Cookies = cookieContainer.GetCookies(new Uri(url)).Cast<Cookie>().ToList(),
                        StatusCode = response.StatusCode,
                        IsSuccessStatusCode = ((int)response.StatusCode >= 200 && (int)response.StatusCode <= 299),
                    };
                    if (callback != null)
                        callback(result);
                    //close and dispose response
#if NETFX
                    response.Close();
#endif
                    response.Dispose();
                    //give result back
                    return result;
                }
                else
                    return default(RequestResult);
            }
            catch (Exception ex)
            {
                DebugEx.TraceError(ex, "Http request failed");
                return default(RequestResult);
            }
        }
Ejemplo n.º 5
0
 public static RequestResult Request(HttpMethods method, string url, string data, HttpRequestDataFormat dataFormat, Dictionary<string, string> headers, IEnumerable<Cookie> Cookies, ICredentials Credentials, Action<RequestResult> callback, ProgressReportDelegate progressReportCallback)
 {
     return _Request(method, url, data != null ? Encoding.UTF8.GetBytes(data) : null, dataFormat, headers, Cookies, Credentials, callback, progressReportCallback);
 }
Ejemplo n.º 6
0
 public static Task<RequestResult> RequestAsync(HttpMethods method, string url, string data, HttpRequestDataFormat dataFormat, Dictionary<string, string> headers, IEnumerable<Cookie> Cookies, Action<RequestResult> callback)
 {
     return Task.Run(() => Request(method, url, data, dataFormat, headers, Cookies, null, callback, null));
 }
Ejemplo n.º 7
0
 public static RequestResult Request(HttpMethods method, string url, string data, HttpRequestDataFormat dataFormat, Dictionary<string, string> headers, IEnumerable<Cookie> Cookies, ICredentials Credentials)
 {
     return Request(method, url, data, dataFormat, headers, Cookies, Credentials, null, null);
 }
Ejemplo n.º 8
0
 public static RequestResult Request(HttpMethods method, string url, string data, HttpRequestDataFormat dataFormat, ICredentials Credentials)
 {
     return Request(method, url, data, dataFormat, null, null, Credentials, null, null);
 }