Exemplo n.º 1
0
 public RouteInfo(object controller, HTTPMethodType methodType, PathToRegex pathToRoute, DefaultRouter.RouterCallback routerCallback)
 {
     Controller     = controller;
     MethodType     = methodType;
     PathToRegex    = pathToRoute;
     RouterCallback = routerCallback;
 }
Exemplo n.º 2
0
    private IEnumerator CoroutineSendRequest(string path, HTTPMethodType methodType, JsonData body, Action <SHReply> callback)
    {
        ShowIndicator();

        UnityWebRequest www = CreateRequestData(path, methodType, body);

        yield return(www.SendWebRequest());

        CloseIndicator();

        callback(new SHReply(www));
    }
Exemplo n.º 3
0
    private UnityWebRequest CreateRequestData(string path, HTTPMethodType methodType, JsonData body)
    {
        Uri uri = new Uri(WebHost + path);

        if (HTTPMethodType.GET == methodType)
        {
            var keyValueParamList = new List <string>();

            if (null != body)
            {
                foreach (var key in body.Keys)
                {
                    // EscapeURL : URL에 사용하는 문자열로 인코딩 : 특수문자에 대해 16진수코드값으로 변환,,
                    keyValueParamList.Add(key + "=" + UnityWebRequest.EscapeURL(body[key].ToJson()));
                }
            }

            uri = new Uri(new Uri(WebHost),
                          string.Format("{0}?{1}", path.TrimEnd('/'), string.Join("&", keyValueParamList.ToArray())));
        }

        string bodyString = GetBodyMessage(body);

        UnityWebRequest request;

        if (HTTPMethodType.GET == methodType)
        {
            request = UnityWebRequest.Get(uri.AbsoluteUri);
        }
        else
        {
            request = new UnityWebRequest(uri.AbsoluteUri);
            request.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(bodyString));
        }

        request.method             = methodType.ToString();
        request.downloadHandler    = new DownloadHandlerBuffer();
        request.certificateHandler = new SHCustomCertificateHandler();
        request.timeout            = 3;

        Debug.LogFormat("[REQUEST] : {0} {1}\nbody = {2}", methodType, uri.OriginalString, bodyString);

        request.SetRequestHeader("Content-Type", "application/json; charset=utf-8");
        request.SetRequestHeader("Accept", "application/json");
        //request.SetRequestHeader("Authorization", JWTHeader.GetAuthorizationString());
        request.useHttpContinue = false;

        return(request);
    }
Exemplo n.º 4
0
        public void SendToRestServiceWithBody(string name, string url, HTTPMethodType method, RequestDto requestDto)
        {
            variableController.Variables.Should().NotContainKey($"Данные по сервису с именем \"{name}\" уже существуют");
            serviceController.Services.Should().NotContainKey($"Данные по сервису с именем \"{name}\" уже существуют");

            url = variableController.ReplaceVariables(url);

            if (requestDto.Query.Any())
            {
                url = url.AddQueryInURL(requestDto.Query);
            }

            if (!Uri.TryCreate(url, UriKind.Absolute, out _))
            {
                Log.Logger().LogWarning($"Url {url} is not valid.");
                throw new ArgumentException($"Url {url} is not valid.");
            }

            var request = new RequestInfo
            {
                Content    = requestDto.Content,
                Headers    = requestDto.Header,
                Credential = requestDto.Credentials,
                Timeout    = requestDto.Timeout,
                Method     = webMethods[method],
                Url        = url
            };

            using var service = new WebService();

            var responce = service.SendMessage(request).Result;

            if (responce != null)
            {
                serviceController.Services.TryAdd(name, responce);
            }
            else
            {
                Log.Logger().LogInformation($"Сервис с названием \"{name}\" не добавлен. Подробности в логах");
            }
        }
Exemplo n.º 5
0
        /// <summary>
        ///     요청을 처리하여 매칭되는 RouterCallback을 호출합니다.
        /// </summary>
        /// <returns>Response에 클라에 보내질 문자열.</returns>
        public object Route(HttpListenerRequest request, ISerializer serializer)
        {
            var            uri        = request.Url;
            var            url        = uri.AbsolutePath;
            HTTPMethodType methodType = request.GetHTTPMethod();

            RouteInfo targetRouteInfo = null;

            foreach (var routeInfo in RouteInfos)
            {
                if (!routeInfo.IsMatched(methodType, url))
                {
                    continue;
                }
                targetRouteInfo = routeInfo;
            }

            if (targetRouteInfo == null)
            {
                return("wrong path");
            }
            return(targetRouteInfo.RouterCallback(request, targetRouteInfo, serializer));
        }
Exemplo n.º 6
0
        public void SendToRestServiceWithBody(string name, string url, HTTPMethodType method, RequestDto requestDto)
        {
            this.variableController.Variables.ContainsKey(name).Should().BeFalse($"Данные по сервису с именем \"{name}\" уже существуют");
            this.serviceController.Services.ContainsKey(name).Should().BeFalse($"Данные по сервису с именем \"{name}\" уже существуют");

            //Добавляем query к Url
            if (requestDto.Query.Any())
            {
                url = ServiceHelpers.AddQueryInURL(url, requestDto.Query.Values.First());
            }

            if (!Uri.TryCreate(url, UriKind.Absolute, out Uri outUrl))
            {
                Log.Logger().LogWarning($"Url {url} is not valid.");
                throw new ArgumentException($"Url {url} is not valid.");
            }

            var request = new RequestInfo
            {
                Content = requestDto.Content,
                Headers = requestDto.Header,
                Method  = webMethods[method],
                Url     = url
            };

            using (var service = new WebService(request))
            {
                var responce = service.SendMessage(request);

                if (responce != null)
                {
                    this.serviceController.Services.TryAdd(name, responce);
                    this.variableController.SetVariable(name, responce.Content.GetType(), responce.Content);
                }
            }
        }
Exemplo n.º 7
0
 public bool IsMatched(HTTPMethodType methodType, string url)
 {
     return(MethodType == methodType && PathToRegex.IsMatched(url));
 }
Exemplo n.º 8
0
 public void SendRequest(string path, HTTPMethodType methoodType, JsonData body, Action <SHReply> callback)
 {
     StartCoroutine(CoroutineSendRequest(path, methoodType, body, callback));
 }
Exemplo n.º 9
0
 public RouteAttribute(HTTPMethodType httpMethodType, string routeUrl)
 {
     HttpMethodType = httpMethodType;
     URLPattern     = routeUrl;
 }