Exemple #1
0
        protected virtual JObject PostAction(AipHttpRequest aipReq)
        {
            var respStr = SendRequet(aipReq);
//		    Console.WriteLine(respStr);
            JObject respObj;

            try
            {
                respObj = JsonConvert.DeserializeObject(respStr) as JObject;
            }
            catch (Exception e)
            {
                // 非json应该抛异常
                throw new AipException(e.Message + ": " + respStr);
            }

            if (respObj == null)
            {
                throw new AipException("Empty response, please check input");
            }

            // 服务失败,不抛异常
//	        if (respObj["error_code"] != null)
//	        {
//	            Console.WriteLine((string)respObj["error_msg"]);
//	            throw new AipException((int)respObj["error_code"], (string)respObj["error_msg"]);
//	        }
            return(respObj);
        }
Exemple #2
0
        /// <summary>
        ///     签名 host 和 Content-Type
        /// </summary>
        /// <param name="aipHttpRequest"></param>
        /// <returns></returns>
        private static string CanonicalRequest(AipHttpRequest aipHttpRequest)
        {
            var uri = aipHttpRequest.Uri;

            var canonicalUri    = Utils.UriEncode(uri.AbsolutePath);
            var canonicalQuerys = aipHttpRequest.Querys
                                  .Where(pair => !pair.Key.Equals("authorization"))
                                  .Select(pair =>
                                          new KeyValuePair <string, string>(Utils.UriEncode(pair.Key), Utils.UriEncode(pair.Value)))
                                  .ToList()
                                  .OrderBy(pair => pair.Key)
                                  .Select(pair => string.Format("{0}={1}", pair.Key, Utils.UriEncode(pair.Value, true)))
                                  .DefaultIfEmpty("")
                                  .Aggregate((a, b) => a + "&" + b);


            var host = uri.Host;

            if (!(uri.Scheme == "https" && uri.Port == 443) && !(uri.Scheme == "http" && uri.Port == 80))
            {
                host += ":" + uri.Port;
            }
            var canonicalHeaders = "content-type:" + Utils.UriEncode(aipHttpRequest.GeneratedRequest.ContentType, true)
                                   + "\nhost:" + Utils.UriEncode(host);
//			var canonicalHeaders = "host:" + Utils.UriEncode(host);

            var canonicalRequest = string.Format("{0}\n{1}\n{2}\n{3}",
                                                 aipHttpRequest.Method, canonicalUri, canonicalQuerys, canonicalHeaders);

            return(canonicalRequest);
        }
 protected virtual HttpWebRequest GenerateWebRequest(AipHttpRequest aipRequest)
 {
     Console.WriteLine(IsDev);
     return(IsDev
         ? aipRequest.GenerateDevWebRequest(Token, Timeout)
         : aipRequest.GenerateCloudRequest(ApiKey, SecretKey, Timeout));
 }
        protected HttpWebResponse SendRequetRaw(AipHttpRequest aipRequest)
        {
            var webReq = GenerateWebRequest(aipRequest);

            webReq.KeepAlive = true;
            Log(webReq.RequestUri.ToString());
            HttpWebResponse resp;

            try
            {
                resp = (HttpWebResponse)webReq.GetResponse();
            }
            catch (WebException e)
            {
                Console.WriteLine(e.ToString());
                // 网络请求失败应该抛异常
                throw new AipException((int)e.Status, e.Message);
            }

            if (resp.StatusCode != HttpStatusCode.OK)
            {
                throw new AipException((int)resp.StatusCode, "Server response code:" + (int)resp.StatusCode);
            }

            return(resp);
        }
Exemple #5
0
        protected HttpWebResponse SendRequetRaw(AipHttpRequest aipRequest)
        {
            HttpWebRequest  webReq = null;
            HttpWebResponse resp   = null;

            try
            {
                webReq = GenerateWebRequest(aipRequest);
                Log(webReq.RequestUri.ToString());
                resp = (HttpWebResponse)webReq.GetResponse();
            }
            catch (WebException e)
            {
                // 网络请求失败应该抛异常
                throw new AipException((int)e.Status, e.Message);
            }
            finally
            {
                webReq?.Abort();
            }

            if (resp.StatusCode != HttpStatusCode.OK)
            {
                throw new AipException((int)resp.StatusCode, "Server response code:" + (int)resp.StatusCode);
            }

            return(resp);
        }
Exemple #6
0
        protected async Task <string> SendRequet(AipHttpRequest aipRequest)
        {
            HttpResponseMessage resp = await SendRequetRaw(aipRequest);

            return(await resp.Content.ReadAsStringAsync());

            //  return Utils.StreamToString(SendRequetRaw(aipRequest).GetResponseStream(), aipRequest.ContentEncoding);
        }
Exemple #7
0
 // common service for all interface
 /// <summary>
 /// 反馈接口
 /// 用于用户反馈模型的效果,用户必须至少反馈一个 true/false 来表示对该结果是否满意,同时可选择反馈详细的评价。
 /// http://ai.baidu.com/docs#/ImageCensoring-API/top
 /// </summary>
 /// <param name="data">
 /// demo: 具体参考文档
 ///    {
 ///        "api_url": "https://aip.baidubce.com/rest/2.0/antiporn/v1/detect",
 ///        "image_logid": 123456,
 ///        "level": 1,
 ///        "correct": 1
 ///    }
 /// </param>
 /// <returns></returns>
 public JObject Report(IEnumerable<Dictionary<string, object>> data)
 {
     var aipReq = new AipHttpRequest("https://aip.baidubce.com/rpc/2.0/feedback/v1/report")
     {
         Method = "POST",
         BodyType = AipHttpRequest.BodyFormat.Json    
     };
     CheckNotNull(data, "data");
     aipReq.Bodys["feedback"] = data;
     PreAction();
     return PostAction(aipReq);
 }
Exemple #8
0
        public static void CloudRequest(AipHttpRequest aipReq, string ak, string sk)
        {
            var now = DateTime.Now;
            var expirationInSeconds = 1200;

            var signDate         = now.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ssK");
            var authStringPrefix = "bce-auth-v1/" + ak + "/" + signDate + "/" + expirationInSeconds;
            var signingKey       =
                Hex(new HMACSHA256(Encoding.UTF8.GetBytes(sk)).ComputeHash(Encoding.UTF8.GetBytes(authStringPrefix)));

            var canonicalRequestString = CanonicalRequest(aipReq);

            var signature =
                Hex(new HMACSHA256(Encoding.UTF8.GetBytes(signingKey)).ComputeHash(
                        Encoding.UTF8.GetBytes(canonicalRequestString)));

            // 签名content-type 与 host
            var authorization = authStringPrefix + "/content-type;host/" + signature;

            aipReq.GeneratedRequest.Headers.Add("x-bce-date", signDate);
            aipReq.GeneratedRequest.Headers.Add("Authorization", authorization);
        }
        protected virtual JObject PostAction(AipHttpRequest aipReq)
        {
            var     respStr = SendRequet(aipReq);
            JObject respObj;

            try
            {
                respObj = JsonConvert.DeserializeObject(respStr) as JObject;
            }
            catch (Exception e)
            {
                // 非json应该抛异常
                throw new AipException(e.Message + ": " + respStr);
            }

            if (respObj == null)
            {
                throw new AipException("Empty response, please check input");
            }

            return(respObj);
        }
Exemple #10
0
        protected async Task <HttpResponseMessage> SendRequetRaw(AipHttpRequest aipRequest)
        {
            var webReq = GenerateWebRequest(aipRequest);

            Log(webReq.RequestUri.ToString());
            HttpResponseMessage resp;

            try
            {
                resp = await apiClient.SendAsync(webReq);
            }
            catch (HttpRequestException e)
            {
                // 网络请求失败应该抛异常
                throw new AipException((int)100, e.Message);
            }

            if (resp.StatusCode != HttpStatusCode.OK)
            {
                throw new AipException((int)resp.StatusCode, "Server response code:" + (int)resp.StatusCode);
            }

            return(resp);
        }
Exemple #11
0
 protected string SendRequet(AipHttpRequest aipRequest)
 {
     return(Utils.StreamToString(SendRequetRaw(aipRequest).GetResponseStream(), aipRequest.ContentEncoding));
 }
Exemple #12
0
 protected virtual HttpWebRequest GenerateWebRequest(AipHttpRequest aipRequest)
 {
     return(IsDev
         ? aipRequest.GenerateDevWebRequest(Token)
         : aipRequest.GenerateCloudRequest(ApiKey, SecretKey));
 }