Exemple #1
0
        internal async Task <string> HttpGetAsync(string oauthUrl, IDictionary <string, string> parameters)
        {
            var req = new HttpRequestMessage(HttpMethod.Get, oauthUrl);

            req.Headers.Add("Authorization", GetAuthorizationString(HttpMethod.Get, oauthUrl, parameters));
            req.Headers.Add("User-Agent", UserAgent);
            req.Headers.ExpectContinue = false;

            var handler = new HttpClientHandler();

            if (handler.SupportsAutomaticDecompression)
            {
                handler.AutomaticDecompression = DecompressionMethods.GZip;
            }
            if (Proxy != null && handler.SupportsProxy)
            {
                handler.Proxy = Proxy;
            }

            var msg = await new HttpClient(handler).SendAsync(req).ConfigureAwait(false);

            await TwitterErrorHandler.ThrowIfErrorAsync(msg).ConfigureAwait(false);

            return(await msg.Content.ReadAsStringAsync().ConfigureAwait(false));
        }
Exemple #2
0
        async Task GetBearerTokenAsync()
        {
            var req = new HttpRequestMessage(System.Net.Http.HttpMethod.Post, OAuth2Token);

            req.Headers.Add("Authorization", "Basic " + BasicToken);
            req.Headers.Add("User-Agent", UserAgent);
            req.Headers.ExpectContinue = false;
            req.Content = new StringContent("grant_type=client_credentials", Encoding.UTF8, "application/x-www-form-urlencoded");

            var handler = new HttpClientHandler();

            if (handler.SupportsAutomaticDecompression)
            {
                handler.AutomaticDecompression = DecompressionMethods.GZip;
            }
            if (Proxy != null && handler.SupportsProxy)
            {
                handler.Proxy = Proxy;
            }

            using (var client = new HttpClient(handler))
            {
                var msg = await client.SendAsync(req).ConfigureAwait(false);

                await TwitterErrorHandler.ThrowIfErrorAsync(msg);

                string response = await msg.Content.ReadAsStringAsync().ConfigureAwait(false);

                var responseJson = JsonMapper.ToObject(response);
                BearerToken = responseJson.GetValue <string>("access_token");
            }
        }
        internal async Task <string> HttpPostAsync(string oauthUrl, IDictionary <string, string> parameters)
        {
            var postData =
                (from keyValPair in parameters
                 where !keyValPair.Key.StartsWith("oauth")
                 select keyValPair)
                .ToDictionary(pair => pair.Key, pair => pair.Value);

            var req = new HttpRequestMessage(HttpMethod.Post, oauthUrl);

            req.Headers.Add("Authorization", GetAuthorizationString(HttpMethod.Post.ToString(), oauthUrl, parameters));
            req.Headers.Add("User-Agent", UserAgent);
            req.Headers.ExpectContinue = false;

            var paramString =
                string.Join("&",
                            (from parm in postData
                             select parm.Key + "=" + Url.PercentEncode(parm.Value))
                            .ToList());
            var content = new StringContent(paramString, Encoding.UTF8, "application/x-www-form-urlencoded");

            req.Content = content;

            var handler = new HttpClientHandler();

            var msg = await new HttpClient(handler).SendAsync(req).ConfigureAwait(false);

            await TwitterErrorHandler.ThrowIfErrorAsync(msg).ConfigureAwait(false);

            return(await msg.Content.ReadAsStringAsync().ConfigureAwait(false));
        }
        public async Task InvalidateAsync()
        {
            EncodeCredentials();

            var req = new HttpRequestMessage(System.Net.Http.HttpMethod.Post, OAuth2InvalidateToken);

            req.Headers.Add("Authorization", "Basic " + BasicToken);
            req.Headers.Add("User-Agent", UserAgent);
            req.Headers.ExpectContinue = false;
            req.Content = new StringContent("access_token=" + BearerToken, Encoding.UTF8, "application/x-www-form-urlencoded");

            var handler = new HttpClientHandler();

            using (var client = new HttpClient(handler))
            {
                var msg = await client.SendAsync(req).ConfigureAwait(false);

                await TwitterErrorHandler.ThrowIfErrorAsync(msg).ConfigureAwait(false);

                string response = await msg.Content.ReadAsStringAsync().ConfigureAwait(false);

                var responseJson = JsonMapper.ToObject(response);
                BearerToken = responseJson.GetValue <string>("access_token");
            }
        }
Exemple #5
0
        async Task GetBearerTokenAsync()
        {
            var req = new HttpRequestMessage(HttpMethod.Post, new Uri(OAuth2Token));

            req.Headers.Add("Authorization", "Basic " + BasicToken);
            req.Headers.Add("User-Agent", UserAgent);
            req.Headers.Add("Expect", "100-continue");
            req.Content = new HttpStringContent("grant_type=client_credentials", Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/x-www-form-urlencoded");

            var baseFilter = new HttpBaseProtocolFilter
            {
                AutomaticDecompression = SupportsCompression,
                ProxyCredential        = ProxyCredential,
                UseProxy = UseProxy
            };

            using (var client = new HttpClient(baseFilter))
            {
                var msg = await client.SendRequestAsync(req);

                await TwitterErrorHandler.ThrowIfErrorAsync(msg);

                string response = await msg.Content.ReadAsStringAsync();

                var responseJson = JsonMapper.ToObject(response);
                BearerToken = responseJson.GetValue <string>("access_token");
            }
        }
        internal async Task <string> HttpGetAsync(string oauthUrl, IDictionary <string, string> parameters)
        {
            var req = new HttpRequestMessage(HttpMethod.Get, oauthUrl);

            req.Headers.Add("Authorization", GetAuthorizationString(HttpMethod.Get.ToString(), oauthUrl, parameters));
            req.Headers.Add("User-Agent", UserAgent);
            req.Headers.ExpectContinue = false;

            var handler = new HttpClientHandler();

            var msg = await new HttpClient(handler).SendAsync(req).ConfigureAwait(false);

            await TwitterErrorHandler.ThrowIfErrorAsync(msg).ConfigureAwait(false);

            return(await msg.Content.ReadAsStringAsync().ConfigureAwait(false));
        }
Exemple #7
0
        async Task <string> HandleResponseAsync(HttpResponseMessage msg)
        {
            LastUrl = msg.RequestMessage.RequestUri;

            ResponseHeaders =
                (from header in msg.Headers
                 select new
            {
                Key = header.Key,
                Value = string.Join(", ", header.Value)
            })
                .ToDictionary(
                    pair => pair.Key,
                    pair => pair.Value);

            await TwitterErrorHandler.ThrowIfErrorAsync(msg).ConfigureAwait(false);

            return(await msg.Content.ReadAsStringAsync());
        }
Exemple #8
0
        internal async Task <string> HttpGetAsync(string oauthUrl, IDictionary <string, string> parameters)
        {
            var req = new HttpRequestMessage(HttpMethod.Get, new Uri(oauthUrl));

            req.Headers.Add("Authorization", GetAuthorizationString(HttpMethod.Get.ToString(), oauthUrl, parameters));
            req.Headers.Add("User-Agent", UserAgent);
            req.Headers.Add("Expect", "100-continue");

            var baseFilter = new HttpBaseProtocolFilter
            {
                AutomaticDecompression = SupportsCompression,
                ProxyCredential        = ProxyCredential,
                UseProxy = UseProxy
            };

            var msg = await new HttpClient(baseFilter).SendRequestAsync(req);

            await TwitterErrorHandler.ThrowIfErrorAsync(msg).ConfigureAwait(false);

            return(await msg.Content.ReadAsStringAsync());
        }
Exemple #9
0
        internal async Task <string> HttpPostAsync(string oauthUrl, IDictionary <string, string> parameters)
        {
            var postData =
                (from keyValPair in parameters
                 where !keyValPair.Key.StartsWith("oauth")
                 select keyValPair)
                .ToDictionary(pair => pair.Key, pair => pair.Value);

            var req = new HttpRequestMessage(HttpMethod.Post, new Uri(oauthUrl));

            req.Headers.Add("Authorization", GetAuthorizationString(HttpMethod.Post.ToString(), oauthUrl, parameters));
            req.Headers.Add("User-Agent", UserAgent);
            req.Headers.Add("Expect", "100-continue");

            var paramString =
                string.Join("&",
                            (from parm in postData
                             select parm.Key + "=" + Url.PercentEncode(parm.Value))
                            .ToList());
            var content = new HttpStringContent(paramString, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/x-www-form-urlencoded");

            req.Content = content;

            var baseFilter = new HttpBaseProtocolFilter
            {
                AutomaticDecompression = SupportsCompression,
                ProxyCredential        = ProxyCredential,
                UseProxy = UseProxy
            };

            var msg = await new HttpClient(baseFilter).SendRequestAsync(req);

            await TwitterErrorHandler.ThrowIfErrorAsync(msg).ConfigureAwait(false);

            return(await msg.Content.ReadAsStringAsync());
        }
Exemple #10
0
        /// <summary>
        /// Performs a query on the Twitter Stream.
        /// </summary>
        /// <param name="request">Request with url endpoint and all query parameters.</param>
        /// <returns>
        /// Caller expects an JSON formatted string response, but
        /// real response(s) with streams is fed to the callback.
        /// </returns>
        public async Task <string> QueryTwitterStreamAsync(Request request)
        {
            const int CarriageReturn = 0x0D;
            const int LineFeed       = 0x0A;
            const int EndOfStream    = 0xFF;

            WriteLog(request.FullUrl, "QueryTwitterStreamAsync");

            IDictionary <string, string> reqParams =
                request.RequestParameters.ToDictionary(key => key.Name, val => val.Value);

            var baseFilter = new HttpBaseProtocolFilter
            {
                AutomaticDecompression = Authorizer.SupportsCompression,
                ProxyCredential        = Authorizer.ProxyCredential,
                UseProxy = Authorizer.UseProxy
            };

            var streamFilter = new GetMessageFilter(this, reqParams, request.FullUrl, baseFilter, CancellationToken);

            using (StreamingClient = new HttpClient(streamFilter))
            {
                var httpRequest = new HttpRequestMessage(HttpMethod.Get, new Uri(request.FullUrl));
                var response    = await StreamingClient.SendRequestAsync(
                    httpRequest, HttpCompletionOption.ResponseHeadersRead);

                await TwitterErrorHandler.ThrowIfErrorAsync(response).ConfigureAwait(false);

                var inputStream = await response.Content.ReadAsInputStreamAsync();

                Stream stream = inputStream.AsStreamForRead();

                var    memStr = new MemoryStream();
                byte[] readByte;

                while (stream.CanRead && !IsStreamClosed)
                {
                    readByte = new byte[1];
                    await stream.ReadAsync(readByte, 0, 1, CancellationToken).ConfigureAwait(false);

                    byte nextByte = readByte.SingleOrDefault();

                    CancellationToken.ThrowIfCancellationRequested();

                    if (IsStreamClosed)
                    {
                        break;
                    }

                    // TODO: review end-of-stream protocol
                    if (nextByte == EndOfStream)
                    {
                        break;
                    }

                    if (nextByte != CarriageReturn && nextByte != LineFeed)
                    {
                        memStr.WriteByte(nextByte);
                    }

                    if (nextByte == LineFeed)
                    {
                        int    byteCount  = (int)memStr.Length;
                        byte[] tweetBytes = new byte[byteCount];

                        memStr.Position = 0;
                        await memStr.ReadAsync(tweetBytes, 0, byteCount, CancellationToken).ConfigureAwait(false);

                        string tweet       = Encoding.UTF8.GetString(tweetBytes, 0, byteCount);
                        var    strmContent = new StreamContent(this, tweet);

                        await StreamingCallbackAsync(strmContent).ConfigureAwait(false);

                        memStr.Dispose();
                        memStr = new MemoryStream();
                    }
                }
            }

            IsStreamClosed = false;

            return("{}");
        }
Exemple #11
0
        /// <summary>
        /// Performs a query on the Twitter Stream.
        /// </summary>
        /// <param name="request">Request with url endpoint and all query parameters.</param>
        /// <returns>
        /// Caller expects an JSON formatted string response, but
        /// real response(s) with streams is fed to the callback.
        /// </returns>
        public async Task <string> QueryTwitterStreamAsync(Request request)
        {
            WriteLog(request.FullUrl, nameof(QueryTwitterStreamAsync));

            var handler = new HttpClientHandler();

            if (Authorizer.Proxy != null && handler.SupportsProxy)
            {
                handler.Proxy = Authorizer.Proxy;
            }

            using (StreamingClient = new HttpClient(handler))
            {
                StreamingClient.Timeout = TimeSpan.FromMilliseconds(System.Threading.Timeout.Infinite);

                var httpRequest = ConfigureRequest(request);

                var response = await StreamingClient.SendAsync(
                    httpRequest, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);

                await TwitterErrorHandler.ThrowIfErrorAsync(response).ConfigureAwait(false);

                Stream stream = await CreateStream(response).ConfigureAwait(false);

                const int CarriageReturn = 0x0D;
                const int LineFeed       = 0x0A;

                var    memStr = new MemoryStream();
                byte[] readByte;

                while (stream.CanRead && !IsStreamClosed)
                {
                    readByte = new byte[1];
                    await stream.ReadAsync(readByte, 0, 1, CancellationToken).ConfigureAwait(false);

                    byte nextByte = readByte.SingleOrDefault();

                    CancellationToken.ThrowIfCancellationRequested();

                    if (IsStreamClosed)
                    {
                        break;
                    }

                    if (nextByte == 0xff)
                    {
                        break;
                    }

                    if (nextByte != CarriageReturn && nextByte != LineFeed)
                    {
                        memStr.WriteByte(nextByte);
                    }

                    if (nextByte == LineFeed)
                    {
                        int    byteCount  = (int)memStr.Length;
                        byte[] tweetBytes = new byte[byteCount];

                        memStr.Position = 0;
                        await memStr.ReadAsync(tweetBytes, 0, byteCount, CancellationToken).ConfigureAwait(false);

                        string tweet       = Encoding.UTF8.GetString(tweetBytes, 0, byteCount);
                        var    strmContent = new StreamContent(this, tweet);

                        await StreamingCallbackAsync(strmContent).ConfigureAwait(false);

                        memStr.Dispose();
                        memStr = new MemoryStream();
                    }
                }
            }

            IsStreamClosed = false;

            return("{}");
        }