Exemplo n.º 1
0
        private async Task <RestClient> GetClient(bool requireAuth = true)
        {
            var client = new RestClient
            {
                JsonSerializerSettings = GetSettings(),
                BaseUrl = VineEndpoints.BaseUrl
            };

            client.AddHeader("accept-language", "en, sv, fr, de, ja, nl, it, es, pt, pt-PT, da, fi, nb, ko, zh-Hans, zh-Hant, ru, pl, tr, uk, ar, hr, cs, el, he, ro, sk, th, id, ms, en-GB, ca, hu, vi, en-us;q=0.8");

            if (requireAuth && (string.IsNullOrWhiteSpace(_username) || string.IsNullOrWhiteSpace(_password)))
            {
                throw new VineSharpConfigurationException();
            }

            if (!requireAuth)
            {
                return(client);
            }

            // authenticate and add headers
            if (_authenticatedUser == null)
            {
                // Authenticate sets the _authenticatedUser property
                var authResult = await Authenticate();

                // set the current authenticated user
                _authenticatedUser = authResult.Data;
            }

            client.AddHeader("vine-session-id", _authenticatedUser.Key);

            return(client);
        }
        public HammockHttpClient(Uri baseUri, string username, string password)
        {
            this.client = new RestClient { Authority = baseUri.ToString() };

            client.AddHeader("Accept", "application/json");
            client.AddHeader("Content-Type", "application/json; charset=utf-8");

            client.ServicePoint = System.Net.ServicePointManager.FindServicePoint(baseUri);
            client.ServicePoint.SetTcpKeepAlive(true, 300, 30);

            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            {
                var credentials = username + ":" + password;
                var base64Credentials = Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials));
                client.AddHeader("Authorization", "Basic " + base64Credentials);
            }

            client.RetryPolicy = new RetryPolicy
            {
                RetryConditions =
                {
                    new Hammock.Retries.NetworkError(),
                    new Hammock.Retries.Timeout(),
                    new Hammock.Retries.ConnectionClosed()
                },
                RetryCount = 3
            };

            client.BeforeRetry += new EventHandler<RetryEventArgs>(client_BeforeRetry);
        }
Exemplo n.º 3
0
        public HammockHttpClient(Uri baseUri, string username, string password)
        {
            this.client = new RestClient {
                Authority = baseUri.ToString()
            };

            client.AddHeader("Accept", "application/json");
            client.AddHeader("Content-Type", "application/json; charset=utf-8");

            client.ServicePoint = System.Net.ServicePointManager.FindServicePoint(baseUri);
            client.ServicePoint.SetTcpKeepAlive(true, 300, 30);

            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            {
                var credentials       = username + ":" + password;
                var base64Credentials = Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials));
                client.AddHeader("Authorization", "Basic " + base64Credentials);
            }

            client.RetryPolicy = new RetryPolicy
            {
                RetryConditions =
                {
                    new Hammock.Retries.NetworkError(),
                    new Hammock.Retries.Timeout(),
                    new Hammock.Retries.ConnectionClosed()
                },
                RetryCount = 3
            };

            client.BeforeRetry += new EventHandler <RetryEventArgs>(client_BeforeRetry);
        }
Exemplo n.º 4
0
        static Base()
        {
            settings = new JsonSerializerSettings
            {
                MissingMemberHandling = MissingMemberHandling.Ignore,
                NullValueHandling     = NullValueHandling.Include,
                DefaultValueHandling  = DefaultValueHandling.Include,
                Converters            = new List <JsonConverter>()
                {
                    new PaginatedListConvertor <Player>("players"),
                    new PaginatedListConvertor <Shot>("shots"),
                    new PaginatedListConvertor <Comment>("comments"),
                }
            };

            serializer = new DribbbleSerializer(settings);

            client = new RestClient
            {
                Authority = "http://api.dribbble.com",
            };

            client.AddHeader("Accept", "application/json");
            client.AddHeader("Content-Type", "application/json; charset=utf-8");
            client.AddHeader("User-Agent", "DribbbleDotNet");
        }
Exemplo n.º 5
0
        private void postMessageToTwitter()
        {
            var credentials = new OAuthCredentials
            {
                Type              = OAuthType.ProtectedResource,
                SignatureMethod   = OAuthSignatureMethod.HmacSha1,
                ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
                ConsumerKey       = AppSettings.TwitterConsumerKey,
                ConsumerSecret    = AppSettings.TwitterConsumerKeySecret,
                Token             = this.accessToken,
                TokenSecret       = this.accessTokenSecret,
                Version           = "1.0"
            };

            var restClient = new RestClient
            {
                Authority = AppSettings.TwitterStatusUpdateUrl,
                HasElevatedPermissions = true,
                Credentials            = credentials,
                Method = WebMethod.Post
            };

            restClient.AddHeader("Content-Type", "application/x-www-form-urlencoded");

            var restRequest = new RestRequest
            {
                Path = "1/statuses/update.xml?status=" + this.postMessage
            };

            var ByteData = Encoding.UTF8.GetBytes(this.postMessage);

            restRequest.AddPostContent(ByteData);
            restClient.BeginRequest(restRequest, new RestCallback(postFinished));
        }
Exemplo n.º 6
0
        public async Task <UrbanDictionaryEntry> GetEntryAsync(string term, int index = 0)
        {
            RestClient client = new RestClient("https://mashape-community-urban-dictionary.p.mashape.com/define?term=" + term);

            client.AddHeader("X-Mashape-Key", key);
            client.AddHeader("Accept", "application/json");

            RestResponse <UrbanDictionaryResponse> post = await client.GetAsync <UrbanDictionaryResponse>("");

            if (post.Data.Entries.Count == 0)
            {
                return(null);
            }

            return(post.Data.Entries.FirstOrDefault());
        }
Exemplo n.º 7
0
 private void Start()
 {
     _restClient = new RestClient(Url, HealthCheckResource);
     foreach (var header in Headers)
     {
         _restClient.AddHeader(header.key, header.value);
     }
 }
Exemplo n.º 8
0
        public HammockHttpClient(Uri baseUri, string username, string password, TimeSpan timeout, bool shouldInitConnection)
        {
            this.client = new RestClient {
                Authority = baseUri.ToString()
            };

            client.AddHeader("Accept", "application/json");
            client.AddHeader("Content-Type", "application/json; charset=utf-8");

            client.ServicePoint = System.Net.ServicePointManager.FindServicePoint(baseUri);
#if !MONO
            client.ServicePoint.SetTcpKeepAlive(true, 300, 30);
#endif
            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            {
                var credentials       = username + ":" + password;
                var base64Credentials = Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials));
                client.AddHeader("Authorization", "Basic " + base64Credentials);
            }

            client.Timeout     = timeout;
            client.RetryPolicy = new RetryPolicy
            {
                RetryConditions =
                {
                    new Hammock.Retries.NetworkError(),
                    new Hammock.Retries.Timeout(),
                    new Hammock.Retries.ConnectionClosed()
                },
                RetryCount = 3
            };

            client.BeforeRetry += new EventHandler <RetryEventArgs>(client_BeforeRetry);

            //The first time a request is made to a URI, the ServicePointManager
            //will create a ServicePoint to manage connections to a particular host
            //This process is expensive and slows down the first created view.
            //The call to BeginRequest is basically an async, no-op HTTP request to
            //initialize the ServicePoint before the first view request is made.
            if (shouldInitConnection)
            {
                client.BeginRequest();
            }
        }
        public HammockHttpClient(Uri baseUri, string username, string password, TimeSpan timeout, bool shouldInitConnection)
        {
            this.client = new RestClient { Authority = baseUri.ToString() };

            client.AddHeader("Accept", "application/json");
            client.AddHeader("Content-Type", "application/json; charset=utf-8");

            client.ServicePoint = System.Net.ServicePointManager.FindServicePoint(baseUri);
            #if ! MONO
            client.ServicePoint.SetTcpKeepAlive(true, 300, 30);
            #endif
            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            {
                var credentials = username + ":" + password;
                var base64Credentials = Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials));
                client.AddHeader("Authorization", "Basic " + base64Credentials);
            }

            client.Timeout = timeout;
            client.RetryPolicy = new RetryPolicy
            {
                RetryConditions =
                {
                    new Hammock.Retries.NetworkError(),
                    new Hammock.Retries.Timeout(),
                    new Hammock.Retries.ConnectionClosed()
                },
                RetryCount = 3
            };

            client.BeforeRetry += new EventHandler<RetryEventArgs>(client_BeforeRetry);

            //The first time a request is made to a URI, the ServicePointManager
            //will create a ServicePoint to manage connections to a particular host
            //This process is expensive and slows down the first created view.
            //The call to BeginRequest is basically an async, no-op HTTP request to
            //initialize the ServicePoint before the first view request is made.
            if (shouldInitConnection) client.BeginRequest();
        }
Exemplo n.º 10
0
        /// <summary>
        /// 上传数据
        /// </summary>
        /// <param name="url"></param>
        /// <param name="service"></param>
        /// <param name="queries"></param>
        /// <param name="action"></param>
        /// <param name="failed"></param>
        protected void UploadString(string url
            , IDictionary<string, string> queries
            , Action<RestResponse, object> action
            , Action<Exception> failed
            , object userState)
        {
            bool httpResult = HttpWebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
            RestClient client = new RestClient();
            client.Method = WebMethod.Post;
            queries.ToList().ForEach(o => client.AddParameter(o.Key, o.Value));
            client.AddHeader("X-Requested-With", "xmlhttp");

            client.Authority = url;
            RestRequest restRequest = new RestRequest();
            CookieContainer cookieContainer = null;
            if (IsolatedStorageSettings.ApplicationSettings.Contains("cookie"))
            {
                cookieContainer = IsolatedStorageSettings.ApplicationSettings["cookieContainer"] as CookieContainer;
                Cookie cookie = IsolatedStorageSettings.ApplicationSettings["cookie"] as Cookie;
                if (cookieContainer.Count == 0 && cookie != null)
                {
                    cookieContainer.SetCookies(new Uri(Constant.ROOTURL), string.Format("{0}={1}", cookie.Name, cookie.Value));
                }
            }
            else
            {
                cookieContainer = new CookieContainer();
            }

            restRequest.CookieContainer = cookieContainer;
            client.BeginRequest(restRequest, (request, response, userState1) =>
            {
                cookieContainer = response.CookieContainer;
                CookieCollection cookies = cookieContainer.GetCookies(new Uri(Constant.ROOTURL));
                try
                {
                    IsolatedStorageSettings.ApplicationSettings["cookie"] = cookies["cooper"];
                    IsolatedStorageSettings.ApplicationSettings["cookieContainer"] = cookieContainer;
                    IsolatedStorageSettings.ApplicationSettings.Save();
                }
                catch
                {
                }

                if (response != null)
                    Deployment.Current.Dispatcher.BeginInvoke(action, response, userState1);
                else
                    Deployment.Current.Dispatcher.BeginInvoke(failed, new Exception("response返回为空!"));
            }, userState);
        }
        public HammockHttpClient(Uri baseUri)
        {
            this.client = new RestClient { Authority = baseUri.ToString() };

            client.AddHeader("Accept", "application/json");
            client.AddHeader("Content-Type", "application/json; charset=utf-8");

            client.ServicePoint = System.Net.ServicePointManager.FindServicePoint(baseUri);
            client.ServicePoint.SetTcpKeepAlive(true, 300, 30);

            client.RetryPolicy = new RetryPolicy
            {
                RetryConditions =
                {
                    new Hammock.Retries.NetworkError(),
                    new Hammock.Retries.Timeout(),
                    new Hammock.Retries.ConnectionClosed()
                },
                RetryCount = 3
            };

            client.BeforeRetry += new EventHandler<RetryEventArgs>(client_BeforeRetry);
        }
Exemplo n.º 12
0
        private RestClient BuildClient(bool isLogin, bool isAuthentication)
        {
            Uri currentTargetUri = isLogin ? _credentialManager.LoginTarget : _credentialManager.CurrentTarget;

            string baseUrl = currentTargetUri.AbsoluteUri;

            var rv = new RestClient
            {
                BaseUrl = baseUrl,
            };

            if (isAuthentication && _credentialManager.HasToken)
            {
                rv.AddHeader("AUTHORIZATION", string.Format("{0} {1}", _credentialManager.CurrentToken.TokenType,
                                                            _credentialManager.CurrentToken.Token));
            }
            else if (isLogin)
            {
                byte[] encodedBytes = Encoding.UTF8.GetBytes(Constants.DefaultLogin);
                var    defaultLogin = string.Format("Basic {0}", Convert.ToBase64String(encodedBytes));
                rv.AddHeader("AUTHORIZATION", defaultLogin);
            }
            return(rv);
        }
Exemplo n.º 13
0
        public void Can_request_get_with_header_on_client()
        {
            var client = new RestClient
            {
                Authority            = "https://api.twitter.com",
                UserAgent            = "Hammock",
                Path                 = "statuses/public_timeline.json",
                DecompressionMethods = DecompressionMethods.GZip | DecompressionMethods.Deflate
            };

            client.AddHeader("Accept", "application/json");

            var response = client.Request();

            Assert.IsNotNull(response);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
        }
Exemplo n.º 14
0
        public void Can_request_get_with_header_on_client()
        {
            var client = new RestClient
            {
                Authority = "https://api.twitter.com",
                UserAgent = "Hammock",
                Path = "statuses/public_timeline.json",
                DecompressionMethods = DecompressionMethods.GZip | DecompressionMethods.Deflate
            };

            client.AddHeader("Accept", "application/json");
            
            var response = client.Request();

            Assert.IsNotNull(response);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
        }
Exemplo n.º 15
0
        private void EstablishStream()
        {
            m_oaCredentials.Verifier = null;
            m_oaCredentials.Type     = OAuthType.ProtectedResource;

            //construct and open streaming request
            RestRequest rrqRequest = new RestRequest
            {
                Path = C_USER_STREAM_URL,
            };

            m_rcClient.AddHeader("User-Agent", "Twitter/1.0");

            //@TODO: uncomment these for production
            m_iaConnectionAsync = m_rcClient.BeginRequest(rrqRequest, RequestCallback);
            m_rcClient.CancelStreaming();  //don't know why this is necessary - maybe it isn't?
        }
Exemplo n.º 16
0
        public WowClient(string baseUrl, IAuthenticator authenticator, int apiVersion, string application)
        {
            Client = new RestClient()
            {
                BaseUrl = baseUrl,
                UserAgent = "wow.ApiLibrary/" + application
            };

            Client.JsonSerializerSettings = new Newtonsoft.Json.JsonSerializerSettings
            {
                Error = (sender, e) =>
                {
                    Debug.WriteLine(e.ToString());
                },
                ConstructorHandling = Newtonsoft.Json.ConstructorHandling.AllowNonPublicDefaultConstructor
            };

            Client.AddHeader("api-version", apiVersion.ToString());
            authenticator.SetAuthentication(Client);
        }
Exemplo n.º 17
0
 public MikiApiClient(string token)
 {
     _client = new RestClient(_baseUrl);
     _client.AddHeader("Authorization", "Bearer " + token);
 }
Exemplo n.º 18
0
        public static void Tweet(string tweet)
        {
            var credentials = new OAuthCredentials
            {
                Type = OAuthType.ProtectedResource,
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
                ConsumerKey = TwitterSettings.ConsumerKey,
                ConsumerSecret = TwitterSettings.ConsumerKeySecret,
                Token = IsolatedStorageSettings.ApplicationSettings[TWITTER_ACCESS_TOKEN_KEY].ToString(),     //The request Token
                TokenSecret = IsolatedStorageSettings.ApplicationSettings[TWITTER_ACCESS_SECRET_KEY].ToString(), 
                Version = "1.0"
            };

            var restClient = new RestClient
            {
                Authority = TwitterSettings.StatusUpdateUrl,
                HasElevatedPermissions = true,
                Credentials = credentials,
                Method = WebMethod.Post
            };

            restClient.AddHeader("Content-Type", "application/x-www-form-urlencoded");

            // Create a Rest Request and fire it
            var restRequest = new RestRequest
            {
                Path = "1/statuses/update.xml?status=" +  tweet 
            };

            var ByteData = Encoding.UTF8.GetBytes(tweet);
            restRequest.AddPostContent(ByteData);
            restClient.BeginRequest(restRequest, new RestCallback(TweetCallback));

        }
Exemplo n.º 19
0
 /// <summary>
 /// Sets the authentication.
 /// </summary>
 /// <param name="client">The client.</param>
 public void SetAuthentication(RestClient client)
 {
     client.AddHeader("_username", _username);
     client.AddHeader("_password", _password);
 }
Exemplo n.º 20
0
        private void postMessageToTwitter()
        {
            var credentials = new OAuthCredentials
            {
                Type = OAuthType.ProtectedResource,
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
                ConsumerKey = AppSettings.TwitterConsumerKey,
                ConsumerSecret = AppSettings.TwitterConsumerKeySecret,
                Token = this.accessToken,
                TokenSecret = this.accessTokenSecret,
                Version = "1.0"
            };

            var restClient = new RestClient
            {
                Authority = AppSettings.TwitterStatusUpdateUrl,
                HasElevatedPermissions = true,
                Credentials = credentials,
                Method = WebMethod.Post
            };

            restClient.AddHeader("Content-Type", "application/x-www-form-urlencoded");

            var restRequest = new RestRequest
            {
                Path = "1/statuses/update.xml?status=" + this.postMessage
            };

            var ByteData = Encoding.UTF8.GetBytes(this.postMessage);
            restRequest.AddPostContent(ByteData);
            restClient.BeginRequest(restRequest, new RestCallback(postFinished));
        }