示例#1
0
文件: WebClientX.cs 项目: yangyx91/X
        /// <summary>创建客户端会话</summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        protected virtual HttpWebRequest Create(String uri)
        {
            var req = WebRequest.Create(uri) as HttpWebRequest;

            req.UserAgent = UserAgent;

            if (AutomaticDecompression != DecompressionMethods.None)
            {
                req.AutomaticDecompression = AutomaticDecompression;
            }

            if (!Accept.IsNullOrEmpty())
            {
                req.Accept = Accept;
            }
            if (!AcceptLanguage.IsNullOrEmpty())
            {
                req.Headers[HttpRequestHeader.AcceptLanguage + ""] = AcceptLanguage;
            }
            if (!Referer.IsNullOrEmpty())
            {
                req.Referer = Referer;
            }

            return(req);
        }
 /// <summary>
 /// Initializes a new instance of the ThiqahRestClient using None Authentication mode
 /// </summary>
 /// <param name="baseURL">The base URL used for all operations</param>
 /// <param name="acceptLanguage">The Accept-Language request HTTP header to determine which language the client uses</param>
 /// <param name="generateAPIException">if true the service return APIEception if false it will return a GeneralException</param>
 public ThiqahRestClient(string baseURL, AcceptLanguage acceptLanguage, bool generateAPIException)
 {
     this.BaseURL              = baseURL;
     this.AcceptLanguage       = acceptLanguage;
     this.generateAPIException = generateAPIException;
     this.AuthenticationMode   = AuthenticationMode.None;
 }
        /// <summary>
        /// Classifies an image based on a given set of classifiers, or all classifiers if no classifiers are specified.
        /// </summary>
        /// <param name="url">The URL of an image (.jpg, or .png). Redirects are followed, so you can use shortened
        ///                   URLs. The resolved URL is returned in the response. Maximum image size is 2 MB.</param>
        /// <param name="acceptLanguage">(Optional) Specifies the language of the output. You can specify en for English,
        ///                              es for Spanish, ar for Arabic, or ja for Japanese. Classifiers for which no 
        ///                              translation is available are ommitted.  Default value is English.</param>
        /// <param name="threshold">(Optional) A floating value that specifies the minimum score a class must have to be
        ///                         displayed in the response. Setting the threshold to 0.0 will return all values, 
        ///                         regardless of their classification score.</param>
        /// <param name="owners">(Optional) A Collection with the value(s) ClassifierOwner.IBM and/or ClassifierOwner.Me
        ///                      to specify which classifiers to run.</param>
        /// <param name="classifierIds">(Optional) Array of classifier Ids to use when classifying the image</param>
        /// <returns>A collection of images and their corresponding classifier scores</returns>
        public async Task<ClassifyResponse> ClassifyAsync(string url,
            AcceptLanguage acceptLanguage = AcceptLanguage.EN,
            double? threshold = null,
            ICollection<ClassifierOwner> owners = null,
            params string[] classifierIds)
        {
            ClassifyResponse model = new ClassifyResponse();

            // Create an HttpClient to make the request using VrClient()
            using (var client = VrClient())
            {
                try
                {
                    var requestString = "api/v3/classify";

                    // add API key
                    requestString += "?api_key=" + _vrCreds.ApiKey;
                    // add API version
                    requestString += "&version=" + VersionReleaseDate;
                    // add URL
                    requestString += "&url=" + url;

                    // convert the classifierIds array to a comma-separated list and add it to the request
                    if (classifierIds?.Any() == true && classifierIds[0] != null)
                    {
                        requestString += "&classifier_ids=" + string.Join(",", classifierIds);
                    }

                    // convert the owners array to a comma-separated list and add it to the request
                    if (owners?.Any() == true)
                    {
                        requestString += "&owners=" + string.Join(",", owners.Select(m => m == ClassifierOwner.IBM ? m.ToString() : m.ToString().ToLowerInvariant()).ToList());
                    }

                    // if threshold was not omitted, add it to the request
                    if (threshold.HasValue)
                    {
                        requestString += "&threshold=" + threshold.Value.ToString("F2");
                    }

                    // set accepted languages in headers
                    client.DefaultRequestHeaders.AcceptLanguage.Clear();
                    client.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue(acceptLanguage.ToString().ToLowerInvariant()));

                    // send a GET request to the Watson service
                    var response = await client.GetAsync(requestString);

                    // if the request succeeded, read the json result as a Response object
                    if (response.IsSuccessStatusCode)
                    {
                        model = await response.Content.ReadAsAsync<ClassifyResponse>();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.StackTrace);
                }
            }
            return model;
        }
        public void BuildRequestMessage_AcceptLanguageHeader_Equal(AcceptLanguage acceptLanguage)
        {
            var options = new ProfileOptions("Hello World") {AcceptLanguage = acceptLanguage};
            var requestBuilder = new ProfileRequestBuilder();
            var message = requestBuilder.BuildRequestMessage(ServiceUrl, options, false);

            Assert.Equal($"{acceptLanguage}".ToLower(), message.Headers.AcceptLanguage.First().Value);
        }
 /// <summary>
 /// Initializes a new instance of the ThiqahRestClient using Basic Authentication
 /// </summary>
 /// <param name="baseURL">The base URL used for all operations</param>
 /// <param name="acceptLanguage">The Accept-Language request HTTP header to determine which language the client uses</param>
 /// <param name="username">An identification used by the client to access the API</param>
 /// <param name="password">A password is a word or string of characters used for authentication to prove identity or access approval to gain access to the API. which is to be kept secret from those not allowed access.</param>
 /// <param name="generateAPIException">if true the service return APIEception if false it will return a GeneralException</param>
 public ThiqahRestClient(string baseURL, AcceptLanguage acceptLanguage, string username, string password, bool generateAPIException)
 {
     this.BaseURL              = baseURL;
     this.AcceptLanguage       = AcceptLanguage;
     this.Username             = username;
     this.Password             = password;
     this.AuthenticationMode   = AuthenticationMode.Basic;
     this.generateAPIException = generateAPIException;
 }
示例#6
0
        /// <summary>创建客户端会话</summary>
        /// <returns></returns>
        public virtual HttpClientX EnsureCreate()
        {
            var http = _client;

            if (http == null)
            {
                var p = Proxy;
                if (p == null && !ProxyAddress.IsNullOrEmpty())
                {
                    Proxy = p = new WebProxy(ProxyAddress);
                }
                if (p == null)
                {
                    http = new HttpClientX();
                }
                else
                {
                    http = new HttpClientX(new HttpClientHandler {
                        Proxy = p
                    });
                }

                _client      = http;
                Request      = http.DefaultRequestHeaders;
                http.Timeout = new TimeSpan(0, 0, 0, 0, Timeout);
            }

            var req = http.DefaultRequestHeaders;

            if (!UserAgent.IsNullOrEmpty())
            {
                req.UserAgent.ParseAdd(UserAgent);
            }
            if (!Accept.IsNullOrEmpty())
            {
                req.Accept.ParseAdd(Accept);
            }
            if (!AcceptLanguage.IsNullOrEmpty())
            {
                req.AcceptLanguage.ParseAdd(AcceptLanguage);
            }
            if (AutomaticDecompression != DecompressionMethods.None)
            {
                req.AcceptEncoding.ParseAdd("gzip, deflate");
            }
            if (!Referer.IsNullOrEmpty())
            {
                req.Referrer = new Uri(Referer);
            }

            GetCookie();

            return(http);
        }
示例#7
0
        /// <summary>创建客户端会话</summary>
        /// <returns></returns>
        protected virtual HttpClientX Create()
        {
            var http = _client;

            if (http == null)
            {
                http         = _client = new HttpClientX();
                Request      = http.DefaultRequestHeaders;
                http.Timeout = new TimeSpan(0, 0, 0, 0, Timeout);
            }

            var req = http.DefaultRequestHeaders;

            if (!UserAgent.IsNullOrEmpty())
            {
                req.UserAgent.ParseAdd(UserAgent);
            }
            if (!Accept.IsNullOrEmpty())
            {
                req.Accept.ParseAdd(Accept);
            }
            if (!AcceptLanguage.IsNullOrEmpty())
            {
                req.AcceptLanguage.ParseAdd(AcceptLanguage);
            }
            if (AutomaticDecompression != DecompressionMethods.None)
            {
                req.AcceptEncoding.ParseAdd("gzip, deflate");
            }
            if (!Referer.IsNullOrEmpty())
            {
                req.Referrer = new Uri(Referer);
            }

            GetCookie();

            return(http);
        }
示例#8
0
文件: WebClientX.cs 项目: yangyx91/X
        /// <summary>创建客户端会话</summary>
        /// <returns></returns>
        public virtual HttpClient EnsureCreate()
        {
            var http = _client;

            if (http == null)
            {
                var p = Proxy;
                if (p == null && !ProxyAddress.IsNullOrEmpty())
                {
                    Proxy = p = new WebProxy(ProxyAddress);
                }

                var handler = new HttpClientHandler();
                if (p != null)
                {
                    handler.UseProxy = true;
                    handler.Proxy    = p;
                }
                else
                {
                    handler.UseProxy = false;
                    handler.Proxy    = null;
                }
                if (AutomaticDecompression != DecompressionMethods.None)
                {
                    handler.AutomaticDecompression = AutomaticDecompression;
                }

                http = new HttpClient(handler);

                _client      = http;
                Request      = http.DefaultRequestHeaders;
                http.Timeout = new TimeSpan(0, 0, 0, 0, Timeout);
            }

            var req = http.DefaultRequestHeaders;

            if (!UserAgent.IsNullOrEmpty())
            {
                req.UserAgent.ParseAdd(UserAgent);
            }
            if (!Accept.IsNullOrEmpty())
            {
                req.Accept.ParseAdd(Accept);
            }
            if (!AcceptLanguage.IsNullOrEmpty())
            {
                req.AcceptLanguage.ParseAdd(AcceptLanguage);
            }
            if (AutomaticDecompression != DecompressionMethods.None)
            {
                req.AcceptEncoding.ParseAdd("gzip, deflate");
            }
            if (!Referer.IsNullOrEmpty())
            {
                req.Referrer = new Uri(Referer);
            }
            if (KeepAlive)
            {
                req.Connection.ParseAdd("keep-alive");
            }

            GetCookie(http);

            return(http);
        }
        /// <summary>
        /// Classifies an image based on a given set of classifiers, or all classifiers if no classifiers are specified.
        /// </summary>
        /// <param name="filename">The name of the image file to be classified</param>
        /// <param name="fileContents">A byte-array containing the contents of the image file to be classified</param>
        /// <param name="acceptLanguage">(Optional) Specifies the language of the output. You can specify en for English,
        ///                              es for Spanish, ar for Arabic, or ja for Japanese. Classifiers for which no 
        ///                              translation is available are ommitted.  Default value is English.</param>
        /// <param name="threshold">(Optional) A floating value that specifies the minimum score a class must have to be
        ///                         displayed in the response. Setting the threshold to 0.0 will return all values, 
        ///                         regardless of their classification score.</param>
        /// <param name="owners">(Optional) A Collection with the value(s) ClassifierOwner.IBM and/or ClassifierOwner.Me
        ///                      to specify which classifiers to run.</param>
        /// <param name="classifierIds">(Optional) Array of classifier Ids to use when classifying the image</param>
        /// <returns>A collection of images and their corresponding classifier scores</returns>
        public async Task<ClassifyResponse> ClassifyAsync(string filename,
            byte[] fileContents,
            AcceptLanguage acceptLanguage = AcceptLanguage.EN,
            double? threshold = null,
            ICollection<ClassifierOwner> owners = null,
            params string[] classifierIds)
        {
            ClassifyResponse model = new ClassifyResponse();

            // Create an HttpClient to make the request using VrClient()
            using (var client = VrClient())
            {
                try
                {
                    var parameters = new ClassifyParameters();

                    // if classifierIds was not omitted, convert the array to a comma-separated list and add it to the request
                    if (classifierIds != null && classifierIds.Any() && classifierIds[0] != null)
                    {
                        parameters.ClassifierIds = classifierIds;
                    }

                    // if owners was not omitted, convert the array to a comma-separated list and add it to the request
                    if (owners != null && owners.Any())
                    {
                        parameters.Owners = owners;
                    }

                    // if threshold was not omitted, add it to the request
                    if (threshold.HasValue)
                    {
                        parameters.Threshold = threshold.Value.ToString("F2");
                    }

                    // set accepted languages in headers
                    client.DefaultRequestHeaders.AcceptLanguage.Clear();
                    client.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue(acceptLanguage.ToString().ToLowerInvariant()));

                    // create request object
                    HttpContent imageContent = GetHttpContentFromImage(filename, fileContents);
                    MultipartFormDataContent request = CreateFileUploadRequest(GetHttpContentFromParameters(parameters), imageContent);

                    // send a POST request to the Watson service with the form data from request
                    var response = await client.PostAsync("api/v3/classify?api_key=" + _vrCreds.ApiKey + "&version=" + VersionReleaseDate, request);

                    // if the request succeeded, read the json result as a Response object
                    if (response.IsSuccessStatusCode)
                    {
                        var jsonData = await response.Content.ReadAsStringAsync();
                        model = JsonConvert.DeserializeObject<ClassifyResponse>(jsonData);
                    }
                    else
                    {
                        var responseMessage = await response.Content.ReadAsStringAsync();
                        model.Error = new ErrorResponse()
                        {
                            Description = responseMessage
                        };
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.StackTrace);
                }
            }
            return model;
        }
示例#10
0
        /// <summary>创建头部</summary>
        /// <param name="length"></param>
        /// <returns></returns>
        protected override String BuildHeader(Int32 length)
        {
            if (Method.IsNullOrEmpty())
            {
                Method = length > 0 ? "POST" : "GET";
            }

            // 分解主机和资源
            var host = "";
            var uri  = Url;

            if (uri == null)
            {
                uri = new Uri("/");
            }

            if (uri.Scheme.EqualIgnoreCase("http", "ws"))
            {
                if (uri.Port == 80)
                {
                    host = uri.Host;
                }
                else
                {
                    host = "{0}:{1}".F(uri.Host, uri.Port);
                }
            }
            else if (uri.Scheme.EqualIgnoreCase("https"))
            {
                if (uri.Port == 443)
                {
                    host = uri.Host;
                }
                else
                {
                    host = "{0}:{1}".F(uri.Host, uri.Port);
                }
            }

            // 构建头部
            var sb = Pool.StringBuilder.Get();

            sb.AppendFormat("{0} {1} HTTP/1.1\r\n", Method, uri.PathAndQuery);
            sb.AppendFormat("Host:{0}\r\n", host);

            if (!Accept.IsNullOrEmpty())
            {
                sb.AppendFormat("Accept:{0}\r\n", Accept);
            }
            if (Compressed)
            {
                sb.AppendLine("Accept-Encoding:gzip, deflate");
            }
            if (!AcceptLanguage.IsNullOrEmpty())
            {
                sb.AppendFormat("AcceptLanguage:{0}\r\n", AcceptLanguage);
            }
            if (!UserAgent.IsNullOrEmpty())
            {
                sb.AppendFormat("User-Agent:{0}\r\n", UserAgent);
            }

            // 内容长度
            if (length > 0)
            {
                sb.AppendFormat("Content-Length:{0}\r\n", length);
            }
            if (!ContentType.IsNullOrEmpty())
            {
                sb.AppendFormat("Content-Type:{0}\r\n", ContentType);
            }

            if (KeepAlive)
            {
                sb.AppendLine("Connection:keep-alive");
            }
            if (!Referer.IsNullOrEmpty())
            {
                sb.AppendFormat("Referer:{0}\r\n", Referer);
            }

            foreach (var item in Headers)
            {
                sb.AppendFormat("{0}:{1}\r\n", item.Key, item.Value);
            }

            sb.AppendLine();

            return(sb.Put(true));
        }
示例#11
0
        /// <summary>
        /// Makes the actual request to the api based on the full path and, optionally, a request object for the api body.
        /// </summary>
        /// <typeparam name="T">The type of object that the response will be converted to.</typeparam>
        /// <param name="path">The full url including the query string to call</param>
        /// <param name="request">Optional: The Request body that will be converted to JSON.</param>
        /// <param name="reqmethod">The request method. POST for authentication seems to be the only case.</param>
        /// <returns>The deserialized object sent by the server.</returns>
        private async Task <T> MakeRequestAsync <T>(string path, ITVDBRequest request, Requestmethods reqmethod = Requestmethods.get) where T : ITVDBResponse
        {
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(baseurl + path);

            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Accept      = "application/json";

            if (AcceptLanguage != null && AcceptLanguage.Trim().Length > 0)
            {
                httpWebRequest.Headers[HttpRequestHeader.AcceptLanguage] = AcceptLanguage;
            }

            if (Token != null && DateTime.Now < TokenExpiresOn)
            {
                httpWebRequest.Headers[HttpRequestHeader.Authorization] = "Bearer " + Token;
                //httpWebRequest.Credentials = //Authorization: Bearer
            }

            switch (reqmethod)
            {
            default:
            case Requestmethods.get:
                httpWebRequest.Method = "GET";
                break;

            case Requestmethods.post:
                httpWebRequest.Method = "POST";
                break;
            }


            if (request != null)
            {
                using (var streamWriter = new StreamWriter(await httpWebRequest.GetRequestStreamAsync()))
                {
                    string json = JsonConvert.SerializeObject(request, jsonsettings);

                    streamWriter.Write(json);
                    //streamWriter.Flush();
                    //streamWriter.Close();
                }
            }
            else
            {
                //httpWebRequest.
                //using (var streamWriter = new StreamWriter(await httpWebRequest.GetRequestStreamAsync())) { }
            }

            T result;
            HttpWebResponse httpResponse;

            try
            {
                httpResponse = (HttpWebResponse)await httpWebRequest.GetResponseAsync();
            }
            catch (WebException we)
            {
                //result = default(T);
                httpResponse = (HttpWebResponse)we.Response;
                //LastError = we.Message;
                //return default(T);
            }

            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                string jsonresult = streamReader.ReadToEnd();

                LastResponseRaw = jsonresult;

                if (jsonresult == null || jsonresult.Trim().Length == 0)
                {
                    LastError = "Response Received but no data from server!";
                    return(default(T));
                }

                result = JsonConvert.DeserializeObject <T>(jsonresult);
            }

            if (result.Error != null)
            {
                LastError = result.Error;
            }
            return(result);
        }
示例#12
0
 /// <summary>
 /// Initializes a new instance of the ThiqahRestClient using Token based authentication
 /// </summary>
 /// <param name="baseURL">The base URL used for all operations</param>
 /// <param name="acceptLanguage">The Accept-Language request HTTP header  to determine which language the client use</param>
 /// <param name="token">API token is a unique identifier of an application requesting access to your service.</param>
 /// <param name="customHeaderList">This is a list will define the extra headers need to be added to the request header.</param>
 /// <param name="generateAPIException">if true the service return APIEception if false it will return a GeneralException</param>
 public ThiqahRestClient(string baseURL, AcceptLanguage acceptLanguage, string token, bool generateAPIException, List <RequestHeader> customHeaderList) : this(baseURL, acceptLanguage, token, generateAPIException)
 {
     this.CustomHeaderList = customHeaderList;
 }
示例#13
0
 /// <summary>
 /// Initializes a new instance of the ThiqahRestClient using Basic Authentication
 /// </summary>
 /// <param name="baseURL">The base URL used for all operations</param>
 /// <param name="acceptLanguage">The Accept-Language request HTTP header  to determine which language the client use</param>
 /// <param name="username">An identification used by the client to access the API</param>
 /// <param name="password">A password is a word or string of characters used for authentication to prove identity or access approval to gain access to the API. which is to be kept secret from those not allowed access.</param>
 /// <param name="customHeaderList">This is a list will define the extra headers need to be added to the request header.</param>
 /// <param name="generateAPIException">if true the service return APIEception if false it will return a GeneralException</param>
 public ThiqahRestClient(string baseURL, AcceptLanguage acceptLanguage, string username, string password, bool generateAPIException, List <RequestHeader> customHeaderList) : this(baseURL, acceptLanguage, username, password, generateAPIException)
 {
     this.CustomHeaderList = customHeaderList;
 }