示例#1
0
        static void Main(string[] args)
        {
            //@杨中科 封装 负载均衡模板
            //地址:https://github.com/yangzhongke/RuPeng.RestTemplateCore
            //开发完成发布到Nuget:https://www.nuget.org/packages/RestTemplateCore
            // Install-Package RestTemplateCore -Version 1.0.1
            //使用 模板(简单的负载均衡,简化http请求)

            using (HttpClient http = new HttpClient())
            {
                RestTemplate rest = new RestTemplate(http);
                rest.ConsulServerUrl = "http://127.0.0.1:8500";


                #region Post请求
                //SendSms sms = new SendSms() { phoneNum = "119119", msg = "着火了主要火了" };
                //var s = rest.PostAsync("http://MsgService/api/SMS/Send_MI", sms).Result;
                //Console.WriteLine(s.StatusCode);
                #endregion

                #region get请求

                var result = rest.GetForEntityAsync <Product[]>("http://ProductService/api/Product").Result;
                Console.WriteLine(result.StatusCode);
                foreach (var p in result.Body)
                {
                    Console.WriteLine($"id:{p.Id} Name:{p.Name}");
                }
                #endregion
            }
            Console.ReadKey();
        }
示例#2
0
        /// <summary>
        /// RestTemplateCore 方式
        /// </summary>
        /// <returns></returns>
        static async Task RestTemplateCoreAsync()
        {
            using (HttpClient httpClient = new HttpClient())
            {
                RestTemplate rest = new RestTemplate(httpClient);
                Console.WriteLine("---查询数据---------");
                var resp1 = await rest.GetForEntityAsync <Product[]>("http://ProductService/api/Product");

                Console.WriteLine(resp1.StatusCode);
                if (resp1.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    foreach (var p in resp1.Body)
                    {
                        Console.WriteLine($"id={p.Id},name={p.Name}");
                    }
                }
                Console.WriteLine("---新增数据---------");
                Product newP = new Product();
                newP.Id    = 888;
                newP.Name  = "辛增";
                newP.Price = 88.8;
                var resp2 = await rest.PostAsync("http://ProductService/api/Product", newP);

                Console.WriteLine(resp2.StatusCode);
            }
        }
示例#3
0
        static void Main(string[] args)
        {
            using (HttpClient httpClient = new HttpClient())
            {
                RestTemplate rest = new RestTemplate(httpClient, "http://127.0.0.1:8500");

                Console.WriteLine("---querying---------");
                var headers = new HttpRequestMessage().Headers;
                headers.Add("aa", "666");
                var ret1 = rest.GetForEntityAsync <Product[]>("http://ProductService/api/Product/", headers).Result;
                Console.WriteLine(ret1.StatusCode);
                if (ret1.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    foreach (var p in ret1.Body)
                    {
                        Console.WriteLine($"id={p.Id},name={p.Name}");
                    }
                }

                Console.WriteLine("---add new---------");
                Product newP = new Product();
                newP.Id    = 888;
                newP.Name  = "xinzeng";
                newP.Price = 88.8;
                var ret = rest.PostAsync("http://ProductService/api/Product/", newP).Result;
                Console.WriteLine(ret.StatusCode);
            }
            Console.ReadKey();
        }
示例#4
0
        /// <summary>
        /// 根据明信片集合ID获取明信片集合中的所有明信片
        /// </summary>
        /// <param name="envelopeId">明信片集合ID</param>
        /// <param name="success">成功回调函数</param>
        /// <param name="failure">失败回调函数</param>
        public static void GetPostCardByEnvelopeId(string envelopeId, Success <List <PostCardResponse> > success, Failure failure = null)
        {
            var restTemplate = new RestTemplate();

            restTemplate.MessageConverters.Add(new NJsonHttpMessageConverter());

            var nameValueCollection = new Dictionary <string, object>
            {
                { "envelopeId", envelopeId }
            };

            restTemplate.GetForObjectAsync <BodyResponse <Page <PostCardResponse> > >(
                Resources.getPostCardByEnvelopeIdUrl, nameValueCollection,
                resp =>
            {
                if (resp.Error != null)
                {
                    failure?.Invoke(resp.Error.Message);
                    return;
                }
                if (resp.Response.Code < 0)
                {
                    failure?.Invoke(resp.Response.Message);
                    return;
                }
                success?.Invoke(resp.Response.Data.Detail);
            });
        }
示例#5
0
        private static void Main(string[] args)
        {
            using (HttpClient httpClient = new HttpClient())
            {
                RestTemplate rest = new RestTemplate(httpClient);

                Console.WriteLine("---查询数据---------");
                var ret1 = rest.GetForEntityAsync <Product[]>("http://ProductService/api/Product/").Result;
                Console.WriteLine(ret1.StatusCode);
                if (ret1.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    foreach (var p in ret1.Body)
                    {
                        Console.WriteLine($"id={p.Id},name={p.Name}");
                    }
                }

                Console.WriteLine("---新增数据---------");
                Product newP = new Product();
                newP.Id    = 888;
                newP.Name  = "辛增";
                newP.Price = 88.8;
                var ret = rest.PostAsync("http://ProductService/api/Product/", newP).Result;
                Console.WriteLine(ret.StatusCode);
            }
            Console.ReadKey();
        }
示例#6
0
        static void Main(string[] args)
        {
            using (var http = new HttpClient())
            {
                SendSms sms = new SendSms
                {
                    Msg      = "hello",
                    PhoneNum = "188"
                };
                RestTemplate rest = new RestTemplate(http);
                rest.ConsulServerUrl = "http://127.0.0.1:8500";
                var result = rest.PostAsync("http://MsgService/api/SMS/Send_MI", sms).Result;
                Console.WriteLine(result.StatusCode);

                var getResult = rest.GetForEntityAsync <Product[]>("http://ProductService/api/Product").Result;
                foreach (var g in getResult.Body)
                {
                    Console.WriteLine(g.Id + " " + g.Name);
                }

                var getResult2 = rest.GetForEntityAsync <Product>("http://ProductService/api/Product/1").Result;
                Console.WriteLine(getResult2.Body.Name);
            }


            Console.ReadKey();
        }
示例#7
0
        public void CheckConsul()
        {
            RestTemplate restTemplate = new RestTemplate();
            var          result       = restTemplate.GetForEntityAsync <string[]>("http://Lucky.Project.API.Service/api/Values").Result;

            Assert.Equal(2, result.Body.Length);
        }
示例#8
0
        public BEService2()
        {
            m_rest = new RestTemplate();

            m_rest.MessageConverters.Add(new FormHttpMessageConverter());
            m_rest.MessageConverters.Add(new StringHttpMessageConverter());
        }
示例#9
0
        public static void GetOrderDetails(DateTime startDate, DateTime endDate, Success <List <OrderResponse> > success, Failure failure = null)
        {
            var restTemplate = new RestTemplate();

            restTemplate.MessageConverters.Add(new NJsonHttpMessageConverter());
            var nameValueCollection = new Dictionary <string, object>
            {
                { "startDate", startDate.ToString("yyyy-MM-dd HH:mm:ss") },
                { "endDate", endDate.ToString("yyyy-MM-dd HH:mm:ss") }
            };

            restTemplate.PostForObjectAsync <BodyResponse <Page <OrderResponse> > >(Resources.getAllOrderUrl, nameValueCollection, (respon =>
            {
                if (respon.Error != null)
                {
                    failure?.Invoke(respon.Error.Message);
                    return;
                }
                if (respon.Response.Code > 0)
                {
                    success?.Invoke(respon.Response.Data.Detail);
                }
                else
                {
                    failure?.Invoke(respon.Response.Message);
                }
            }));
        }
示例#10
0
        /// <summary>
        /// 提交订单
        /// </summary>
        /// <param name="postCards">要提交的订单集合</param>
        /// <param name="success">成功返回的结果</param>
        /// <param name="failure">失败处理逻辑</param>
        public static void SubmitPostCardList(OrderSubmitRequest postCards, Success <String> success, Failure failure = null)
        {
            var restTemplate = new RestTemplate();

            restTemplate.MessageConverters.Add(new NJsonHttpMessageConverter());
            if (Token == null)
            {
                failure?.Invoke("此操作需要登录,当前用户没有登录");
                return;
            }
            //添加请求头Token
            var httpHeaders = new HttpHeaders {
                { "tokenId", Token }
            };
            //
            var headers = new HttpEntity(postCards, httpHeaders);

            restTemplate.PostForObjectAsync <BodyResponse <Object> >(Resources.postCardSubmitUrl, headers, res =>
            {
                if (res.Error != null)
                {
                    failure?.Invoke(res.Error.Message);
                    return;
                }
                if (res.Response.Code > 0)
                {
                    success?.Invoke(res.Response.Message);
                }
                else
                {
                    failure?.Invoke(res.Response.Message);
                }
            });
        }
示例#11
0
        /// <summary>
        /// Enables customization of the <see cref="RestTemplate"/> used to consume provider API resources.
        /// </summary>
        /// <remarks>
        /// An example use case might be to configure a custom error handler.
        /// Note that this method is called after the RestTemplate has been configured with the message converters returned from GetMessageConverters().
        /// </remarks>
        /// <param name="restTemplate">The RestTemplate to configure.</param>
        protected override void ConfigureRestTemplate(RestTemplate restTemplate)
        {
            restTemplate.BaseAddress = API_URI_BASE;
#if !WINDOWS_PHONE
            restTemplate.RequestInterceptors.Add(new LinkedInRequestFactoryInterceptor());
#endif
        }
 static void Main(string[] args)
 {
     //获取服务
     using (var consulClient = new ConsulClient(c => c.Address = new Uri("http://127.0.0.1:8500")))
     {
         var services = consulClient.Agent.Services().Result.Response;
         foreach (var service in services.Values)
         {
             Console.WriteLine($"id={service.ID},name={service.Service},ip={service.Address},port={service.Port}");
         }
     }
     //消费服务
     using (HttpClient httpClient = new HttpClient())
     {
         RestTemplate rest = new RestTemplate(httpClient);
         rest.ConsulServerUrl = "http://127.0.0.1:8500";
         var ret1 = rest.GetForEntityAsync <Product[]>("http://ProductService/api/Product/").Result;
         Console.WriteLine(ret1.StatusCode);
         if (ret1.StatusCode == System.Net.HttpStatusCode.OK)
         {
             foreach (var p in ret1.Body)
             {
                 Console.WriteLine($"id={p.Id},name={p.Name}");
             }
         }
     }
 }
        private void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            // Note that you can also use the NJsonHttpMessageConverter based on Json.NET library
            // that supports getting/setting values from JSON directly,
            // without the need to deserialize/serialize to a .NET class.

            IHttpMessageConverter jsonConverter = new DataContractJsonHttpMessageConverter();
            jsonConverter.SupportedMediaTypes.Add(new MediaType("text", "javascript"));

            RestTemplate template = new RestTemplate();
            template.MessageConverters.Add(jsonConverter);

            #if NET_3_5
            template.GetForObjectAsync<GImagesResponse>("https://ajax.googleapis.com/ajax/services/search/images?v=1.0&rsz=8&q={query}",
                r =>
                {
                    if (r.Error == null)
                    {
                        this.ResultsItemsControl.ItemsSource = r.Response.Data.Items;
                    }
                }, this.SearchTextBox.Text);
            #else
            // Using Task Parallel Library (TPL)
            var uiScheduler = System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext();
            template.GetForObjectAsync<GImagesResponse>("https://ajax.googleapis.com/ajax/services/search/images?v=1.0&rsz=8&q={query}", this.SearchTextBox.Text)
                .ContinueWith(task =>
                {
                    if (!task.IsFaulted)
                    {
                        this.ResultsItemsControl.ItemsSource = task.Result.Data.Items;
                    }
                }, uiScheduler); // execute on UI thread
            #endif
        }
        /// <summary>
        /// Creates an OAuth2Template for a given set of client credentials.
        /// </summary>
        /// <param name="clientId">The client identifier.</param>
        /// <param name="clientSecret">The client password.</param>
        /// <param name="authorizeUrl">
        /// The base URL to redirect to when doing authorization code or implicit grant authorization.
        /// </param>
        /// <param name="authenticateUrl">
        /// The URL to redirect to when doing authentication via authorization code grant.
        /// </param>
        /// <param name="accessTokenUrl">
        /// The URL at which an authorization code, refresh token, or user credentials may be exchanged for an access token.
        /// </param>
        /// <param name="useParametersForClientAuthentication">
        /// A value indicating whether to pass client credentials to the provider as parameters
        /// instead of using HTTP Basic authentication.
        /// </param>
        public OAuth2Template(string clientId, string clientSecret, string authorizeUrl, string authenticateUrl, string accessTokenUrl, bool useParametersForClientAuthentication)
        {
            ArgumentUtils.AssertNotNull(clientId, "clientId");
            ArgumentUtils.AssertNotNull(clientSecret, "clientSecret");
            ArgumentUtils.AssertNotNull(authorizeUrl, "authorizeUrl");
            ArgumentUtils.AssertNotNull(accessTokenUrl, "accessTokenUrl");

            this.clientId     = clientId;
            this.clientSecret = clientSecret;

            string clientInfo = "?client_id=" + HttpUtils.UrlEncode(clientId);

            this.authorizeUrl = authorizeUrl + clientInfo;
            if (authenticateUrl != null)
            {
                this.authenticateUrl = authenticateUrl + clientInfo;
            }
            else
            {
                this.authenticateUrl = null;
            }
            this.accessTokenUrl = accessTokenUrl;

            this.restTemplate = this.CreateRestTemplate();

            this.useParametersForClientAuthentication = useParametersForClientAuthentication;
            if (!this.useParametersForClientAuthentication)
            {
                restTemplate.RequestInterceptors.Add(new BasicSigningRequestInterceptor(clientId, clientSecret));
            }
        }
示例#15
0
        public static void UserLogin(string userName, string password, Success <LoginResponse> success, Failure failure = null)
        {
            var restTemplate = new RestTemplate();

            restTemplate.MessageConverters.Add(new NJsonHttpMessageConverter());

            var nameValueCollection = new NameValueCollection
            {
                { "userName", userName },
                { "password", password }
            };

            var httpHeaders = new HttpHeaders {
                { "tokenId", "123456" }
            };

            var headers = new HttpEntity(nameValueCollection, httpHeaders);


            restTemplate.PostForObjectAsync <BodyResponse <LoginResponse> >(Resources.loginUrl, headers, resp =>
            {
                if (resp.Error != null)
                {
                    failure?.Invoke(resp.Error.Message);
                    return;
                }
                if (resp.Response.Code > 0)
                {
                    Token = resp.Response.Data.TokenId;
                    success?.Invoke(resp.Response.Data);
                    return;
                }
                failure?.Invoke(resp.Response.Message);
            });
        }
示例#16
0
        /// <summary>
        /// 获取反面模板列表
        /// </summary>
        /// <param name="success"></param>
        /// <param name="failure"></param>
        public static void GetBackStyleTemplateList(Success <List <BackStyleResponse> > success, Failure failure = null)
        {
            var restTemplate = new RestTemplate();

            restTemplate.MessageConverters.Add(new NJsonHttpMessageConverter());

            restTemplate.GetForObjectAsync <BodyResponse <Page <BackStyleResponse> > >(Resources.backStyleListUrl, response =>
            {
                if (response.Error != null)
                {
                    failure?.Invoke(response.Error.Message);
                }
                else
                {
                    if (response.Response.Code > 0)
                    {
                        success?.Invoke(response.Response.Data.Detail);
                    }
                    else
                    {
                        failure?.Invoke(response.Response.Message);
                    }
                }
            });
        }
示例#17
0
        protected AccessGrant PostForAccessGrant(string accessTokenUrl, NameValueCollection parameters)
        {
            var response = RestTemplate.PostForObject <NameValueCollection>(accessTokenUrl, parameters);
            var expires  = response["expires"];

            return(new AccessGrant(response["access_token"], null, null, expires != null ? new int?(Int32.Parse(expires)) : null));
        }
示例#18
0
        public static void GetOrderInfo(string orderId, Success <OrderResponse> success, Failure failure = null)
        {
            var restTemplate = new RestTemplate();

            restTemplate.MessageConverters.Add(new NJsonHttpMessageConverter());
            var nameValueCollection = new Dictionary <string, object>
            {
                { "orderId", orderId }
            };

            restTemplate.GetForObjectAsync <BodyResponse <OrderResponse> >(Resources.getOrderInfoUrl, nameValueCollection, respon =>
            {
                if (respon.Error != null)
                {
                    failure?.Invoke(respon.Error.Message);
                }
                else if (respon.Response.Code > 0)
                {
                    success?.Invoke(respon.Response.Data);
                }
                else
                {
                    failure?.Invoke(respon.Response.Message);
                }
            });
        }
示例#19
0
        /// <summary>
        /// 修改订单状态
        /// </summary>
        /// <param name="orderId">订单ID</param>
        /// <param name="orderStatus">订单状态</param>
        /// <param name="success">成功回调</param>
        /// <param name="failure">失败回调</param>
        public static void ChangeOrderStatus(string orderId, string orderStatus, Success <OrderResponse> success,
                                             Failure failure = null)
        {
            var restTemplate = new RestTemplate();

            restTemplate.MessageConverters.Add(new NJsonHttpMessageConverter());
            var nameValueCollection = new Dictionary <string, object>
            {
                { "orderId", orderId },
                { "orderStatus", orderStatus }
            };

            var httpHeaders = new HttpHeaders {
                { "tokenId", Token }
            };

            if (Token == null)
            {
                failure?.Invoke("当前没有登录!");
                return;
            }
            var headers = new HttpEntity(nameValueCollection, httpHeaders);

            restTemplate.PostForObjectAsync <BodyResponse <OrderResponse> >(Resources.changeOrderStatusUrl, headers, response =>
            {
                if (response.Error != null)
                {
                    failure?.Invoke(response.Error.Message);
                }
                else
                {
                    success?.Invoke(response.Response.Data);
                }
            });
        }
示例#20
0
        /// <summary>
        /// 根据ID获取明信片集合详细信息
        /// </summary>
        /// <param name="envelopeId">明信片集合ID</param>
        /// <param name="success">成功回调函数</param>
        /// <param name="failure">失败回调函数</param>
        public static void GetEnvelopeInfoById(string envelopeId, Success <EnvelopeResponse> success, Failure failure = null)
        {
            var restTemplate = new RestTemplate();

            restTemplate.MessageConverters.Add(new NJsonHttpMessageConverter());

            var nameValueCollection = new Dictionary <string, object>
            {
                { "envelopeId", envelopeId }
            };

            restTemplate.GetForObjectAsync <BodyResponse <EnvelopeResponse> >(
                Resources.envelopeInfoUrl, nameValueCollection, headCompleted =>
            {
                if (headCompleted.Error != null)
                {
                    failure?.Invoke(headCompleted.Error.Message);
                }
                else
                {
                    if (headCompleted.Response.Code < 0)
                    {
                        failure?.Invoke(headCompleted.Response.Message);
                        return;
                    }
                    success?.Invoke(headCompleted.Response.Data);
                }
            });
        }
示例#21
0
        static void Main(string[] args)
        {
            using (HttpClient http = new HttpClient())
            {
                RestTemplate rest = new RestTemplate(http);
                rest.ConsulServerUrl = "http://127.0.0.1:8500";

                /* SendSms sms = new SendSms();
                 * sms.msg = "您好,欢迎";
                 * sms.phoneNum = "189189";
                 * var resp = rest.PostAsync("http://MsgService/api/SMS/Send_MI", sms).Result;
                 * Console.WriteLine(resp.StatusCode);*/
                /*
                 * var res = rest.GetForEntityAsync<Product[]>("http://ProductService/api/Product").Result;
                 * Console.WriteLine(res.StatusCode);
                 * foreach(var p in res.Body)
                 * {
                 * Console.WriteLine(p.Id+p.Name);
                 * }*/
                var res = rest.GetForEntityAsync <Product>("http://ProductService/api/Product/1").Result;
                Console.WriteLine(res.StatusCode);
                Console.WriteLine(res.Body.Name);
            }

            Console.ReadKey();
        }
示例#22
0
        /// <summary>
        /// 根据订单ID获取所有明信片集合
        /// </summary>
        /// <param name="orderId">订单ID</param>
        /// <param name="success">获取成功的响应结果</param>
        /// <param name="failure">获取失败的响应结果</param>
        public static void GetAllEnvelopeByOrderId(string orderId, Success <List <EnvelopeResponse> > success, Failure failure = null)
        {
            var restTemplate = new RestTemplate();

            restTemplate.MessageConverters.Add(new NJsonHttpMessageConverter());

            var nameValueCollection = new Dictionary <string, object>
            {
                { "orderId", orderId }
            };

            restTemplate.GetForObjectAsync <BodyResponse <Page <EnvelopeResponse> > >(Resources.getAllEnvelopeByOrderIdUrl, nameValueCollection,
                                                                                      resp =>
            {
                if (resp.Error != null)
                {
                    failure?.Invoke(resp.Error.Message);
                }
                else
                {
                    if (resp.Response.Code > 0)
                    {
                        success?.Invoke(resp.Response.Data.Detail);
                    }
                    else
                    {
                        failure?.Invoke(resp.Response.Message);
                    }
                }
            });
        }
示例#23
0
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file">要上传的文件</param>
        /// <param name="success">上传成功的回调函数</param>
        /// <param name="failure">上传失败的回调函数</param>
        public static void Upload(FileInfo file, Success <FileUploadResponse> success, Failure failure)
        {
            var restTemplate = new RestTemplate();

            restTemplate.MessageConverters.Add(new NJsonHttpMessageConverter());
            var dictionary = new Dictionary <string, object>();
            var entity     = new HttpEntity(file);

            dictionary.Add("file", entity);
            restTemplate.PostForObjectAsync <BodyResponse <FileUploadResponse> >(Resources.fileUploadUrl, dictionary,
                                                                                 resp =>
            {
                if (resp.Error != null)
                {
                    failure?.Invoke(resp.Error.Message);
                    return;
                }
                if (resp.Response.Code > 0)
                {
                    success?.Invoke(resp.Response.Data);
                    return;
                }
                failure?.Invoke(resp.Response.Message);
            });
        }
        public void SetUp()
        {
            template = new RestTemplate(uri);
            template.MessageConverters = new List<IHttpMessageConverter>();

            webServiceHost = new WebServiceHost(typeof(TestService), new Uri(uri));
            webServiceHost.Open();
        }
 public RestBucksClient()
 {
     // Create and configure RestTemplate
     restTemplate = new RestTemplate(BaseUrl);
     DataContractHttpMessageConverter xmlConverter = new DataContractHttpMessageConverter();
     xmlConverter.SupportedMediaTypes = new MediaType[]{ new MediaType("application", "vnd.restbucks+xml") };
     restTemplate.MessageConverters.Add(xmlConverter);
 }
        public void SetUp()
        {
            template = new RestTemplate(uri);
            contentType = new MediaType("text", "plain");

            webServiceHost = new WebServiceHost(typeof(TestService), new Uri(uri));
            webServiceHost.Open();
        }
示例#27
0
#pragma warning disable CA1810 // Initialize reference type static fields inline
        static NetGlobalInfo()
#pragma warning restore CA1810 // Initialize reference type static fields inline
        {
            AccessToken  = null;
            RestTemplate = new RestTemplate(Settings.Default.Host);
            RestTemplate.MessageConverters.Add(new NJsonHttpMessageConverter());
            RestTemplate.RequestInterceptors.Add(new RequestAuthorizationInterceptor());
        }
示例#28
0
        public string SearchEmployees()
        {
            RestTemplate _RestTemplate = StartTemplate();

            string response = _RestTemplate.GetForObjectAsync <string>(ClientHelper.UrlSearchEmployeess).Result;

            return(response);
        }
        public void SetUp()
        {
            template    = new RestTemplate(uri);
            contentType = new MediaType("text", "plain");

            webServiceHost = new WebServiceHost(typeof(TestService), new Uri(uri));
            webServiceHost.Open();
        }
示例#30
0
        public void SetUp()
        {
            template = new RestTemplate(uri);
            template.MessageConverters = new List <IHttpMessageConverter>();

            webServiceHost = new WebServiceHost(typeof(TestService), new Uri(uri));
            webServiceHost.Open();
        }
        /// <summary>
        /// Creates a <see cref="MockRestServiceServer"/> instance based on the given <see cref="RestTemplate"/>.
        /// </summary>
        /// <param name="restTemplate">The RestTemplate.</param>
        /// <returns>The created server.</returns>
	    public static MockRestServiceServer CreateServer(RestTemplate restTemplate) 
        {
            ArgumentUtils.AssertNotNull(restTemplate, "restTemplate");

		    MockClientHttpRequestFactory mockRequestFactory = new MockClientHttpRequestFactory();
		    restTemplate.RequestFactory = mockRequestFactory;

		    return new MockRestServiceServer(mockRequestFactory);
	    }
示例#32
0
        public void ConfigureRestTemplate()
        {
            restTemplate = new RestTemplate(ConfigurationManager.AppSettings.Get("BaseURL"));

            requestEntity = new HttpEntity();
            requestEntity.Headers["X-OTX-API-KEY"] = ConfigurationManager.AppSettings.Get("APIKey");
            requestEntity.Headers.Add("User-Agent", ConfigurationManager.AppSettings.Get("UserAgent"));
            requestEntity.Headers.ContentType = MediaType.APPLICATION_JSON;
        }
        public RestBucksClient()
        {
            // Create and configure RestTemplate
            restTemplate = new RestTemplate(BaseUrl);
            DataContractHttpMessageConverter xmlConverter = new DataContractHttpMessageConverter();

            xmlConverter.SupportedMediaTypes = new MediaType[] { new MediaType("application", "vnd.restbucks+xml") };
            restTemplate.MessageConverters.Add(xmlConverter);
        }
        // Configure the REST client used to consume LinkedIn API resources
        protected override void ConfigureRestTemplate(RestTemplate restTemplate)
        {
            restTemplate.BaseAddress = API_URI_BASE;

            /*
            // Register custom interceptor to set "x-li-format: json" header 
            restTemplate.RequestInterceptors.Add(new JsonFormatInterceptor());
             */
        }
示例#35
0
        //【+】4 获取IS4地址
        public string GetIdentityServer()  // 负载均衡 获取IS4地址 使用VPN响应会很慢
        {
            var st = new RestTemplate().ResolveRootUrlAsync("IdentityServer4");

            st.Wait();
            var aat = st.Result;

            return(aat);
        }
示例#36
0
 protected override Task <AccessGrant> PostForAccessGrantAsync(string accessTokenUrl, NameValueCollection request)
 {
     return(RestTemplate.PostForObjectAsync <NameValueCollection>(accessTokenUrl, request)
            .ContinueWith <AccessGrant>(task =>
     {
         var expires = task.Result["expires"];
         return new AccessGrant(task.Result["access_token"], null, null, expires != null ? new int?(Int32.Parse(expires)) : null);
     }));
 }
示例#37
0
        public Registration(RestRequestCreator requestCreator)
        {
            _restTemplate = requestCreator.GetRestTemplate();
            
//            // 20141211
//            // temporary
//            // TODO: think about where to move it
//            var tracingControl = new TracingControl("TmxClient_");
        }
        /// <summary>
        /// Constructs the API template without user authorization. 
        /// This is useful for accessing operations on a provider's API that do not require user authorization.
        /// </summary>
        protected AbstractOAuth1ApiBinding()
        {
            this.isAuthorized = false;
            this.restTemplate = new RestTemplate();
#if !SILVERLIGHT
            ((WebClientHttpRequestFactory)restTemplate.RequestFactory).Expect100Continue = false;
#endif
            this.restTemplate.MessageConverters = this.GetMessageConverters();
            this.ConfigureRestTemplate(this.restTemplate);
        }
        public MovieViewModel()
        {
            CreateMovieCommand = new DelegateCommand(CreateMovie, CanCreateMovie);
            DeleteMovieCommand = new DelegateCommand(DeleteMovie, CanDeleteMovie);

            template = new RestTemplate("http://localhost:12345/Services/MovieService.svc/");
            template.MessageConverters.Add(new DataContractJsonHttpMessageConverter());

            RefreshMovies();
        }
        public void SetUp()
        {
            template = new RestTemplate(uri);
            template.MessageConverters = new List<IHttpMessageConverter>();

            contentType = new MediaType("application", "json");

            webServiceHost = new WebServiceHost(typeof(TestService), new Uri(uri));
            webServiceHost.Open();
        }
        /// <summary>
        /// Constructs the API template with OAuth credentials necessary to perform operations on behalf of a user.
        /// </summary>
        /// <param name="consumerKey">The application's consumer key.</param>
        /// <param name="consumerSecret">The application's consumer secret.</param>
        /// <param name="accessToken">The access token.</param>
        /// <param name="accessTokenSecret">The access token secret.</param>
        protected AbstractOAuth1ApiBinding(String consumerKey, String consumerSecret, String accessToken, String accessTokenSecret)
        {
            this.isAuthorized = true;
            this.restTemplate = new RestTemplate();
#if !SILVERLIGHT
            ((WebClientHttpRequestFactory)restTemplate.RequestFactory).Expect100Continue = false;
#endif
            this.restTemplate.RequestInterceptors.Add(new OAuth1RequestInterceptor(consumerKey, consumerSecret, accessToken, accessTokenSecret));
            this.restTemplate.MessageConverters = this.GetMessageConverters();
            this.ConfigureRestTemplate(this.restTemplate);
        }
        /// <summary>
        /// Constructs the API template with OAuth credentials necessary to perform operations on behalf of a user.
        /// </summary>
        /// <param name="accessToken">The access token.</param>
        protected AbstractOAuth2ApiBinding(String accessToken)
        {
            this.accessToken = accessToken;
            this.restTemplate = new RestTemplate();
#if !SILVERLIGHT
            ((WebClientHttpRequestFactory)restTemplate.RequestFactory).Expect100Continue = false;
#endif
            this.restTemplate.RequestInterceptors.Add(new OAuth2RequestInterceptor(accessToken, this.GetOAuth2Version()));
            this.restTemplate.MessageConverters = this.GetMessageConverters();
            this.ConfigureRestTemplate(this.restTemplate);
        }
示例#43
0
        private void SearchButton_Click(object sender, EventArgs e)
        {
            this.ResultsFlowLayoutPanel.Controls.Clear();

            IHttpMessageConverter njsonConverter = new NJsonHttpMessageConverter();
            njsonConverter.SupportedMediaTypes.Add(new MediaType("text", "javascript"));

            RestTemplate template = new RestTemplate();
            template.MessageConverters.Add(njsonConverter);

            template.GetForObjectAsync<JToken>("https://ajax.googleapis.com/ajax/services/search/images?v=1.0&rsz=8&q={query}",
                delegate(RestOperationCompletedEventArgs<JToken> r)
                {
                    if (r.Error == null)
                    {
                        foreach (JToken jToken in r.Response.Value<JToken>("responseData").Value<JArray>("results"))
                        {
                            PictureBox pBox = new PictureBox();
                            pBox.ImageLocation = jToken.Value<string>("tbUrl");
                            pBox.Height = jToken.Value<int>("tbHeight");
                            pBox.Width = jToken.Value<int>("tbWidth");

                            ToolTip tt = new ToolTip();
                            tt.SetToolTip(pBox, jToken.Value<string>("visibleUrl"));

                            this.ResultsFlowLayoutPanel.Controls.Add(pBox);
                        }
                    }
                }, this.SearchTextBox.Text);

            /*
            template.GetForObjectAsync<GImagesResponse>("https://ajax.googleapis.com/ajax/services/search/images?v=1.0&rsz=8&q={query}",
                delegate(RestOperationCompletedEventArgs<GImagesResponse> r)
                {
                    if (r.Error == null)
                    {
                        foreach (GImage gImage in r.Response.Data.Items)
                        {
                            PictureBox pBox = new PictureBox();
                            pBox.ImageLocation = gImage.ThumbnailUrl;
                            pBox.Height = gImage.ThumbnailHeight;
                            pBox.Width = gImage.ThumbnailWidth;

                            ToolTip tt = new ToolTip();
                            tt.SetToolTip(pBox, gImage.SiteUrl);

                            this.ResultsFlowLayoutPanel.Controls.Add(pBox);
                        }
                    }
                }, this.SearchTextBox.Text);
            */
        }
示例#44
0
 protected override RestTemplate CreateRestTemplate()
 {
     RestTemplate template = new RestTemplate();
     ((WebClientHttpRequestFactory) template.RequestFactory).Expect100Continue = false;
     IList<IHttpMessageConverter> list = new List<IHttpMessageConverter>(2);
     FormHttpMessageConverter item = new FormHttpMessageConverter {
         SupportedMediaTypes = { MediaType.ALL }
     };
     list.Add(item);
     list.Add(new MsJsonHttpMessageConverter());
     template.MessageConverters = list;
     return template;
 }
示例#45
0
        static void Main(string[] args)
        {
            try
            {
                // Configure RestTemplate by adding the new converter to the default list
                RestTemplate template = new RestTemplate();
                template.MessageConverters.Add(new ImageHttpMessageConverter());

                // Get image from url
#if NET_4_0
                Bitmap nuGetLogo = template.GetForObjectAsync<Bitmap>("http://nuget.org/Content/Images/nugetlogo.png").Result;
#else
                Bitmap nuGetLogo = template.GetForObject<Bitmap>("http://nuget.org/Content/Images/nugetlogo.png");
#endif

                // Save image to disk
                string filename = Path.Combine(Environment.CurrentDirectory, "NuGetLogo.png");
                nuGetLogo.Save(filename);
                Console.WriteLine(String.Format("Saved NuGet logo to '{0}'", filename));
            }
#if NET_4_0
            catch (AggregateException ae)
            {
                ae.Handle(ex =>
                {
                    if (ex is HttpResponseException)
                    {
                        Console.WriteLine(((HttpResponseException)ex).GetResponseBodyAsString());
                        return true;
                    }
                    return false;
                });
            }
#else
            catch (HttpResponseException ex)
            {
                Console.WriteLine(ex.GetResponseBodyAsString());
            }
#endif
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
			finally
			{
				Console.WriteLine("--- hit <return> to quit ---");
				Console.ReadLine();
			}
        }
示例#46
0
	    public void SetUp() 
        {
            mocks = new MockRepository();
            requestFactory = mocks.StrictMock<IClientHttpRequestFactory>();
            request = mocks.StrictMock<IClientHttpRequest>();
            response = mocks.StrictMock<IClientHttpResponse>();
            errorHandler = mocks.StrictMock<IResponseErrorHandler>();
            converter = mocks.StrictMock<IHttpMessageConverter>();
            
            IList<IHttpMessageConverter> messageConverters = new List<IHttpMessageConverter>(1);
            messageConverters.Add(converter);

            template = new RestTemplate();
            template.RequestFactory = requestFactory;
            template.MessageConverters = messageConverters;
            template.ErrorHandler = errorHandler;
	    }
示例#47
0
        public virtual RestTemplate GetRestTemplate()
        {
            if (null != _restTemplate) return _restTemplate;
            _restTemplate = new RestTemplate(ClientSettings.Instance.ServerUrl);
            // 20150316
            // _restTemplate.MessageConverters.Add(new NJsonHttpMessageConverter());
            // 20150609
            // _restTemplate.MessageConverters.Add(new NJsonHttpMessageConverter() as IHttpMessageConverter);
            _restTemplate.MessageConverters.Add(new NJsonHttpMessageConverter());
            _restTemplate.MessageConverters.Add(new XElementHttpMessageConverter());
            
            _restTemplate.MessageConverters.Add(new XmlSerializableHttpMessageConverter());
            _restTemplate.MessageConverters.Add(new ResourceHttpMessageConverter());
            _restTemplate.MessageConverters.Add(new StringHttpMessageConverter());

            // 20150604
            var requestFactory = new WebClientHttpRequestFactory {Timeout = 600000};
            _restTemplate.RequestFactory = requestFactory;

            return _restTemplate;
        }
示例#48
0
        public RestClient(string url = null)
        {
            string BaseUrl = string.Empty;
            var httpUrl = Properties.Settings.Default.HttpUrl;
            if (!string.IsNullOrEmpty(httpUrl))
            {
                BaseUrl = httpUrl;
            }
            else
            {
                BaseUrl = RestClient.httpUrl;
                Properties.Settings.Default.HttpUrl = RestClient.httpUrl;
                Properties.Settings.Default.Save();
            }

            BaseUrl = url ?? BaseUrl;

            restTemplate = new RestTemplate(BaseUrl);
            IHttpMessageConverter jsonConverter = new DataContractJsonHttpMessageConverter();
            jsonConverter.SupportedMediaTypes.Add(MediaType.APPLICATION_JSON);
            restTemplate.MessageConverters.Add(jsonConverter);
        }
示例#49
0
        public IList<IStreamableTrack> Search(string searchTerm)
        {
            RestTemplate template = new RestTemplate("http://api.soundcloud.com");
            template.MessageConverters.Add(new DataContractJsonHttpMessageConverter());

            IDictionary<string,object> vars = new Dictionary<string, object>();
            vars.Add("client_id", playerID);
            vars.Add("term", searchTerm);

            var tracks = template.GetForObject<List<Track>>("/tracks.json?client_id={client_id}&order=hotness&q={term}", vars);

            // Remove any tracks that aren't streamable
            tracks.RemoveAll(track => !track.Streamable);

            foreach (var track in tracks)
            {
                // Dodgy hack for now
                track.StreamURL = track.StreamURL + "?client_id=" + playerID;
            }

            return tracks.ConvertAll(input => (IStreamableTrack) input);
        }
		public ArticleTemplate(RestTemplate restTemplate, bool isAuthorized)
			: base(isAuthorized)
		{
			_restTemplate = restTemplate;
		}
		public MediaTemplate(string applicationNamespace, RestTemplate restTemplate, bool isAuthorized)
			: base(applicationNamespace, restTemplate, isAuthorized)
		{
		}
 // Configure the REST client used to consume Twitter API resources
 protected override void ConfigureRestTemplate(RestTemplate restTemplate)
 {
     restTemplate.BaseAddress = API_URI_BASE;
 }
 /// <summary>
 /// Enables customization of the <see cref="RestTemplate"/> used to consume provider API resources.
 /// </summary>
 /// <remarks>
 /// An example use case might be to configure a custom error handler. 
 /// Note that this method is called after the RestTemplate has been configured with the message converters returned from GetMessageConverters().
 /// </remarks>
 /// <param name="restTemplate">The RestTemplate to configure.</param>
 protected override void ConfigureRestTemplate(RestTemplate restTemplate)
 {
     restTemplate.BaseAddress = ApiUriBase;
     restTemplate.ErrorHandler = new BitbucketErrorHandler();
 }
 public UserTemplate(RestTemplate restTemplate, bool isAuthorized)
     : base(isAuthorized)
 {
     _restTemplate = restTemplate;
 }
 public GeoTemplate(RestTemplate restTemplate)
 {
     this.restTemplate = restTemplate;
 }
 /// <summary>
 /// Enables customization of the <see cref="RestTemplate"/> used to consume provider API resources.
 /// </summary>
 /// <remarks>
 /// An example use case might be to configure a custom error handler. 
 /// Note that this method is called after the RestTemplate has been configured with the message converters returned from GetMessageConverters().
 /// </remarks>
 /// <param name="restTemplate">The RestTemplate to configure.</param>
 protected override void ConfigureRestTemplate(RestTemplate restTemplate)
 {
     restTemplate.BaseAddress = API_URI_BASE;
     restTemplate.ErrorHandler = new TwitterErrorHandler();
 }
        /// <summary>
        /// Creates an OAuth2Template.
        /// </summary>
        /// <param name="clientId">The client identifier.</param>
        /// <param name="clientSecret">The client password.</param>
        /// <param name="authorizeUrl">The URL of the provider's authorization endpoint.</param>
        /// <param name="authenticateUrl">The URL of the provider's end-user authorization endpoint.</param>
        /// <param name="accessTokenUrl">The URL of the provider's access token endpoint.</param>
        public OAuth2Template(string clientId, string clientSecret, string authorizeUrl, string authenticateUrl, string accessTokenUrl)
        {
            ArgumentUtils.AssertNotNull(clientId, "clientId");
            ArgumentUtils.AssertNotNull(clientSecret, "clientSecret");
            ArgumentUtils.AssertNotNull(authorizeUrl, "authorizeUrl");
            ArgumentUtils.AssertNotNull(accessTokenUrl, "accessTokenUrl");

            this.clientId = clientId;
            this.clientSecret = clientSecret;

            string clientInfo = "?client_id=" + HttpUtils.UrlEncode(clientId);
            this.authorizeUrl = authorizeUrl + clientInfo;
            if (authenticateUrl != null)
            {
                this.authenticateUrl = authenticateUrl + clientInfo;
            }
            else
            {
                this.authenticateUrl = null;
            }
            this.accessTokenUrl = accessTokenUrl;

            this.restTemplate = this.CreateRestTemplate();
        }
        /// <summary>
        /// Creates the <see cref="RestTemplate"/> used to communicate with the provider's OAuth 2 API.
        /// </summary>
        /// <remarks>
        /// This implementation creates a RestTemplate with a minimal set of HTTP message converters: 
        /// <see cref="FormHttpMessageConverter"/> and <see cref="SpringJsonHttpMessageConverter"/>. 
        /// May be overridden to customize how the RestTemplate is created. 
        /// For example, if the provider returns data in some format other than JSON for form-encoded, 
        /// you might override to register an appropriate message converter. 
        /// </remarks>
        /// <returns>The RestTemplate used to perform OAuth2 calls.</returns>
        protected virtual RestTemplate CreateRestTemplate()
        {
            RestTemplate restTemplate = new RestTemplate();
            //((WebClientHttpRequestFactory)this.restTemplate.RequestFactory).Expect100Continue = false;

            IList<IHttpMessageConverter> converters = new List<IHttpMessageConverter>(2);
            FormHttpMessageConverter formConverter = new FormHttpMessageConverter();
            // Always read NameValueCollection as 'application/x-www-form-urlencoded' even if contentType not set properly by provider
            formConverter.SupportedMediaTypes.Add(MediaType.ALL);
            converters.Add(formConverter);
            converters.Add(new SpringJsonHttpMessageConverter());
            restTemplate.MessageConverters = converters;

            return restTemplate;
        }
 public TimelineTemplate(RestTemplate restTemplate, bool isAuthorized)
     : base(isAuthorized)
 {
     this.restTemplate = restTemplate;
 }
 public BlockTemplate(RestTemplate restTemplate)
 {
     this.restTemplate = restTemplate;
 }