示例#1
0
        public void SetQueryString()
        {
            IHttpQueryString query = new HttpQueryString {
                { "hello", "there" }
            };

            IHttpRequest request = HttpRequest
                                   .New()
                                   .SetQueryString(query);

            Assert.AreEqual("hello=there", request.QueryString.ToString());
        }
示例#2
0
        /// <summary>
        /// Gets an authorization based on the specified <paramref name="state"/> and <paramref name="scope"/>.
        /// </summary>
        /// <param name="state">A unique state for the request.</param>
        /// <param name="scope">The scope of your application.</param>
        /// <returns>The authorization URL.</returns>
        /// <see>
        ///     <cref>https://developers.facebook.com/docs/instagram-basic-display-api/reference/oauth-authorize</cref>
        /// </see>
        public string GetAuthorizationUrl(string state, string scope)
        {
            // Initialize the query string
            IHttpQueryString query = new HttpQueryString {
                { "client_id", ClientId },
                { "redirect_uri", RedirectUri },
                { "response_type", "code" },
                { "scope", scope == null ? string.Empty : string.Join(",", scope) },
                { "state", state }
            };

            // Construct the authorization URL
            return("https://api.instagram.com/oauth/authorize?" + query);
        }
示例#3
0
        /// <summary>
        /// Exchanges the specified long-lived <paramref name="accessToken"/> for a new long-lived access token.
        /// </summary>
        /// <param name="accessToken">The long-lived access token to be exchanged.</param>
        /// <returns>An instance of <see cref="InstagramLongLivedTokenResponse"/> representing the API response.</returns>
        /// <see>
        ///     <cref>https://developers.facebook.com/docs/instagram-basic-display-api/reference/refresh_access_token</cref>
        /// </see>
        public InstagramLongLivedTokenResponse RefreshAccessToken(string accessToken)
        {
            // Initialize the query string
            IHttpQueryString query = new HttpQueryString {
                { "grant_type", "ig_refresh_token" },
                { "access_token", accessToken }
            };

            // Make a GET request to the API
            IHttpResponse response = HttpUtils.Requests.Get("https://graph.instagram.com/refresh_access_token", query);

            // Wrap the raw response
            return(new InstagramLongLivedTokenResponse(response));
        }
        public void Remove()
        {
            HttpQueryString query = new HttpQueryString {
                { "rød", "grød" }
            };

            Assert.AreEqual(1, query.Count);
            Assert.AreEqual("grød", query["rød"]);

            query.Remove("rød");

            Assert.AreEqual(0, query.Count);
            Assert.AreEqual(null, query["rød"]);
        }
        private void BuildRequest()
        {
            HttpQueryString query = new HttpQueryString();

            query.Add(Model.CJ.QueryConstants.WebsiteID, ConfigurationManager.AppSettings["cjSiteID"]);
            query.Add(Model.CJ.QueryConstants.PageNumber, "1");
            query.Add(Model.CJ.QueryConstants.RecordsPerPage, "1000");

            var uri = HttpQueryString.MakeQueryString(new Uri(METHOD, UriKind.Relative), query);

            request = new HttpRequestMessage("GET", uri);

            request.Headers.Add(Model.CJ.QueryConstants.Authorization, ConfigurationManager.AppSettings["cjDeveloperKey"]);
        }
示例#6
0
        /// <summary>
        /// Gets an instance of <see cref="IHttpQueryString"/> representing the GET parameters.
        /// </summary>
        public IHttpQueryString GetQueryString()
        {
            // The place type must be specified
            if (PlaceType == FlickrPlaceType.Unknown)
            {
                throw new PropertyNotSetException("PlaceType");
            }

            // Either "WoeId" or "PlaceId" must be specified
            if (string.IsNullOrEmpty(WoeId + PlaceId))
            {
                throw new PropertyNotSetException("PlaceId");
            }

            HttpQueryString query = new HttpQueryString();

            query.Add("method", "flickr.places.placesForContacts");
            query.Add("place_type_id", (int)PlaceType);
            if (!string.IsNullOrEmpty(WoeId))
            {
                query.Add("woe_id", WoeId);
            }
            if (!string.IsNullOrEmpty(PlaceId))
            {
                query.Add("place_id", WoeId);
            }
            if (Threshold > 0)
            {
                query.Add("threshold", Threshold);
            }
            query.Add("contacts", Contacts == FlickrContactsMode.FriendsAndFamily ? "ff" : "all");
            if (MinUploadDate != null)
            {
                query.Add("min_upload_date", MinUploadDate.UnixTimestamp);
            }
            if (MaxUploadDate != null)
            {
                query.Add("max_upload_date", MaxUploadDate.UnixTimestamp);
            }
            if (MinTakenDate != null)
            {
                query.Add("min_taken_date", MinTakenDate.UnixTimestamp);
            }
            if (MaxTakenDate != null)
            {
                query.Add("max_taken_date", MaxTakenDate.UnixTimestamp);
            }

            return(query);
        }
        /// <summary>
        /// Gets an instance of <see cref="IHttpQueryString"/> representing the GET parameters.
        /// </summary>
        /// <returns>An instance of <see cref="IHttpQueryString"/>.</returns>
        public IHttpQueryString GetQueryString()
        {
            // Define the query string
            IHttpQueryString qs = new HttpQueryString();

            // Add optional parameters
            if (UserId > 0)
            {
                qs.Set("user_id", UserId);
            }
            if (!String.IsNullOrWhiteSpace(ScreenName))
            {
                qs.Set("screen_name", ScreenName);
            }
            if (SinceId > 0)
            {
                qs.Set("since_id", SinceId);
            }
            if (Count > 0)
            {
                qs.Set("count", Count);
            }
            if (MaxId > 0)
            {
                qs.Set("max_id", MaxId);
            }
            if (TrimUser)
            {
                qs.Set("trim_user", "true");
            }
            if (ExcludeReplies)
            {
                qs.Set("exclude_replies", "true");
            }
            if (ContributorDetails)
            {
                qs.Set("contributor_details", "true");
            }
            if (!IncludeRetweets)
            {
                qs.Set("include_rts", "false");
            }
            if (TweetMode != TwitterTweetMode.Compatibility)
            {
                qs.Add("tweet_mode", StringUtils.ToCamelCase(TweetMode));
            }

            return(qs);
        }
        /// <inheritdoc />
        public IHttpRequest GetRequest()
        {
            if (Location == null)
            {
                throw new PropertyNotSetException(nameof(Location));
            }

            // Make sure either Latitude or Longitude are specified ("0,0" is considered invalid)
            if (Math.Abs(Location.Latitude) < double.Epsilon && Math.Abs(Location.Longitude) < double.Epsilon)
            {
                throw new PropertyNotSetException(nameof(Location.Latitude));
            }

            // Initialize the query string
            IHttpQueryString query = new HttpQueryString();

            if (string.IsNullOrWhiteSpace(Query) == false)
            {
                query.Add("query", Query);
            }
            query.Add("location", string.Format(CultureInfo.InvariantCulture, "{0},{1}", Location.Latitude, Location.Longitude));
            if (Radius > 0)
            {
                query.Add("radius", Radius);
            }
            if (string.IsNullOrWhiteSpace(Language) == false)
            {
                query.Add("language", Language);
            }
            if (MinPrice != PlacesPriceLevel.Unspecified)
            {
                query.Add("minprice", (int)MinPrice - 1);
            }
            if (MaxPrice != PlacesPriceLevel.Unspecified)
            {
                query.Add("maxprice", (int)MaxPrice - 1);
            }
            if (string.IsNullOrWhiteSpace(Type) == false)
            {
                query.Add("type", Type);
            }
            if (string.IsNullOrWhiteSpace(PageToken) == false)
            {
                query.Add("pagetoken", PageToken);
            }

            // Create the request
            return(HttpRequest.Get("https://maps.googleapis.com/maps/api/place/textsearch/json", query));
        }
示例#9
0
        /// <inheritdoc />
        public IHttpRequest GetRequest()
        {
            if (string.IsNullOrWhiteSpace(PlaceId))
            {
                throw new PropertyNotSetException(nameof(PlaceId));
            }

            // Initialize the query string
            IHttpQueryString query = new HttpQueryString {
                { "place_id", PlaceId }
            };

            // Create the request
            return(HttpRequest.Get("https://maps.googleapis.com/maps/api/geocode/json", query));
        }
示例#10
0
        /// <summary>
        /// Exchanges the specified short-lived <paramref name="accessToken"/> for a new long-lived access token.
        /// </summary>
        /// <param name="accessToken">The short-lived access token to be exchanged.</param>
        /// <returns>An instance of <see cref="InstagramLongLivedTokenResponse"/> representing the API response.</returns>
        /// <see>
        ///     <cref>https://developers.facebook.com/docs/instagram-basic-display-api/reference/access_token</cref>
        /// </see>
        public InstagramLongLivedTokenResponse GetLongLivedAccessToken(string accessToken)
        {
            // Initialize the query string
            HttpQueryString query = new HttpQueryString {
                { "grant_type", "ig_exchange_token" },
                { "client_secret", ClientSecret },
                { "access_token", accessToken }
            };

            // Make a GET request to the API
            IHttpResponse response = HttpUtils.Requests.Get("https://graph.instagram.com/access_token", query);

            // Wrap the raw response
            return(new InstagramLongLivedTokenResponse(response));
        }
示例#11
0
        public IHttpRequest GetRequest()
        {
            IHttpQueryString query = new HttpQueryString();

            if (StartIndex > 0)
            {
                query.Add("start-index", StartIndex);
            }
            if (MaxResults > 0)
            {
                query.Add("max-results", MaxResults);
            }

            return(HttpRequest.Get("/analytics/v3/management/accounts", query));
        }
        /// <inheritdoc />
        public IHttpRequest GetRequest()
        {
            if (WorkspaceId == 0)
            {
                throw new PropertyNotSetException(nameof(WorkspaceId));
            }

            // Initialize the query string
            IHttpQueryString query = new HttpQueryString {
                { "active", Active.ToLower() }
            };

            // Initialize a new request
            return(HttpRequest.Get($"https://{TogglConstants.Track.HostName}/api/v8/workspaces/{WorkspaceId}/projects", query));
        }
        /// <summary>
        /// Gets an instance of <see cref="IHttpQueryString"/> representing the GET parameters.
        /// </summary>
        public virtual IHttpQueryString GetQueryString()
        {
            HttpQueryString query = new HttpQueryString();

            if (Page > 0)
            {
                query.Add("page", Page);
            }
            if (PerPage > 0)
            {
                query.Add("per_page", PerPage);
            }

            return(query);
        }
示例#14
0
        /// <summary>
        /// Gets an instance of <see cref="IHttpQueryString"/> representing the GET parameters.
        /// </summary>
        public IHttpQueryString GetQueryString()
        {
            // Convert the collection of fields to a string
            string fields = (Fields == null ? string.Empty : Fields.ToString()).Trim();

            // Construct the query string
            IHttpQueryString query = new HttpQueryString();

            if (string.IsNullOrWhiteSpace(fields) == false)
            {
                query.Set("fields", fields);
            }

            return(query);
        }
        /// <summary>
        /// Gets an instance of <see cref="IHttpQueryString"/> representing the GET parameters.
        /// </summary>
        public IHttpQueryString GetQueryString()
        {
            // Get the query string
            IHttpQueryString query = new HttpQueryString();

            // Convert the collection of fields to a string
            string fields = (Fields == null ? "" : Fields.ToString()).Trim();

            // Update the query string
            if (!String.IsNullOrWhiteSpace(fields))
            {
                query.Set("fields", fields);
            }

            return(query);
        }
示例#16
0
        public DataTable SchedulesByUserAndGroups(Guid userId, int currentContractId, string groups)
        {
            HttpQueryString queryString = GetDefaultQueryString();
            Uri             uri         = new Uri(string.Format("{0}/{1}/{2}/{3}", GroupsServiceBaseAddress, "Schedules", currentContractId.ToString(), userId.ToString()));
            DataTable       schedules   = RequestRESTData <DataTable>(queryString, uri);

            StringBuilder sb = new StringBuilder();

            sb.Append("C3GroupId IN (");
            string groupCsv = string.Join(",", groups.ToArray());

            sb.Append(groupCsv);
            sb.Append(")");
            schedules.DefaultView.RowFilter = sb.ToString();
            return(schedules.DefaultView.ToTable());
        }
        /// <summary>
        /// Gets an instance of <see cref="IHttpQueryString"/> representing the GET parameters.
        /// </summary>
        public IHttpQueryString GetQueryString()
        {
            // "GalleryId" must be specified
            if (string.IsNullOrWhiteSpace(GalleryId))
            {
                throw new PropertyNotSetException("GroupId");
            }

            // Append the options to the query string (if specified)
            HttpQueryString query = new HttpQueryString();

            query.Add("method", "flickr.galleries.getInfo");
            query.Add("gallery_id", GalleryId);

            return(query);
        }
示例#18
0
        /// <inheritdoc />
        public IHttpRequest GetRequest()
        {
            // Make sure either Latitude or Longitude are specified ("0,0" is considered invalid)
            if (Math.Abs(Latitude) < double.Epsilon && Math.Abs(Longitude) < double.Epsilon)
            {
                throw new PropertyNotSetException(nameof(Latitude));
            }

            // Initialize the query string
            IHttpQueryString query = new HttpQueryString {
                { "latlng", string.Format(CultureInfo.InvariantCulture, "{0},{1}", Latitude, Longitude) }
            };

            // Create the request
            return(HttpRequest.Get("https://maps.googleapis.com/maps/api/geocode/json", query));
        }
示例#19
0
        /// <summary>
        /// Gets an instance of <see cref="IHttpQueryString"/> representing the GET parameters.
        /// </summary>
        /// <returns>An instance of <see cref="IHttpQueryString"/>.</returns>
        public IHttpQueryString GetQueryString()
        {
            IHttpQueryString qs = new HttpQueryString();

            if (UserId > 0)
            {
                qs.Set("user_id", UserId);
            }
            if (!String.IsNullOrWhiteSpace(ScreenName))
            {
                qs.Set("screen_name", ScreenName);
            }
            if (Reverse)
            {
                qs.Set("reverse", "1");
            }
            return(qs);
        }
示例#20
0
        /// <summary>
        /// Gets an instance of <see cref="IHttpQueryString"/> representing the GET parameters.
        /// </summary>
        public virtual IHttpQueryString GetQueryString()
        {
            HttpQueryString query = new HttpQueryString();

            if (Limit != null && Limit.Value >= 0)
            {
                query.Set("limit", Limit.Value);
            }
            if (Before != null)
            {
                query.Set("before", Before);
            }
            if (After != null)
            {
                query.Set("after", After);
            }
            return(query);
        }
        /// <summary>
        /// Gets an instance of <see cref="IHttpQueryString"/> representing the GET parameters.
        /// </summary>
        public virtual IHttpQueryString GetQueryString()
        {
            HttpQueryString query = new HttpQueryString();

            if (Limit >= 0)
            {
                query.Set("limit", Limit);
            }
            if (Since != null && Since.UnixTimestamp > 0)
            {
                query.Set("since", Since.UnixTimestamp);
            }
            if (Until != null && Until.UnixTimestamp > 0)
            {
                query.Set("until", Until.UnixTimestamp);
            }
            return(query);
        }
示例#22
0
 public PageView Save(PageView pageView)
 {
     if (pageView == null)
     {
         return(null);
     }
     try
     {
         HttpQueryString queryString   = GetDefaultQueryString();
         var             uri           = GetServiceRequestUri(ServiceUriFormats.PageViewSave, ServiceUriFormats.Application, new object[] { pageView.ContractId, pageView.UserId });
         var             savedPageView = PostRESTData <PageView>(queryString, uri, pageView);
         return(savedPageView);
     }
     catch (Exception)
     {
         return(null);
     }
 }
        /// <summary>
        /// Gets an instance of <see cref="IHttpQueryString"/> representing the GET parameters.
        /// </summary>
        /// <returns>An instance of <see cref="IHttpQueryString"/>.</returns>
        public IHttpQueryString GetQueryString()
        {
            IHttpQueryString query = new HttpQueryString();

            if (!IncludeEntities)
            {
                query.Add("include_entities", "false");
            }
            if (SkipStatus)
            {
                query.Add("skip_status", "true");
            }
            if (IncludeEmail)
            {
                query.Add("include_email", "true");
            }
            return(query);
        }
        public void Clone()
        {
            HttpQueryString query = new HttpQueryString {
                { "rød", "grød" }
            };

            HttpQueryString copy = query.Clone();

            Assert.AreEqual(1, copy.Count);

            copy.Add("hello", "world");

            Assert.AreEqual("grød", query["rød"]);
            Assert.AreEqual("grød", copy["rød"]);

            Assert.AreEqual(null, query["hello"]);
            Assert.AreEqual("world", copy["hello"]);
        }
示例#25
0
 public PageView Save(PageView pageView)
 {
     if (pageView == null)
     {
         return(null);
     }
     try
     {
         HttpQueryString queryString = GetDefaultQueryString();
         var             uri         = new Uri(string.Format("{0}/{1}/{2}/{3}/{4}/{5}", ContractsServiceBaseAddress, pageView.ContractId, UsersBaseAddress,
                                                             PageViewServiceBaseAddress, pageView.UserId, "Save"));
         var savedPageView = PostRESTData <PageView>(queryString, uri, pageView);
         return(savedPageView);
     }
     catch (Exception)
     {
         return(null);
     }
 }
        /// <summary>
        /// Gets an instance of <see cref="IHttpQueryString"/> representing the GET parameters.
        /// </summary>
        public IHttpQueryString GetQueryString()
        {
            HttpQueryString query = new HttpQueryString();

            query.Add("method", "flickr.galleries.getList");
            if (!string.IsNullOrWhiteSpace(UserId))
            {
                query.Add("user_id ", UserId);
            }
            if (PerPage > 0)
            {
                query.Add("per_page ", PerPage);
            }
            if (Page > 0)
            {
                query.Add("page ", Page);
            }
            return(query);
        }
示例#27
0
        public EditPage()
        {
            PageService     = SysPageService.Instance;
            TemplateService = SysTemplateService.Instance;
            ModuleService   = SysModuleService.Instance;

            var recordId = HttpQueryString.GetValue("id").ToInt();

            if (recordId <= 0)
            {
                return;
            }

            CurrentPage = SysPageService.Instance.GetByID(recordId);

            if (CurrentPage != null)
            {
                CurrentTemplate = SysTemplateService.Instance.GetByID(CurrentPage.TemplateID);
            }
        }
        public IHttpRequest GetRequest()
        {
            if (string.IsNullOrWhiteSpace(AccountId))
            {
                throw new PropertyNotSetException(nameof(AccountId));
            }

            IHttpQueryString query = new HttpQueryString();

            if (StartIndex > 0)
            {
                query.Add("start-index", StartIndex);
            }
            if (MaxResults > 0)
            {
                query.Add("max-results", MaxResults);
            }

            return(HttpRequest.Get($"/analytics/v3/management/accounts/{AccountId}/webproperties", query));
        }
        /// <summary>
        /// Gets an instance of <see cref="IHttpQueryString"/> representing the GET parameters.
        /// </summary>
        public IHttpQueryString GetQueryString()
        {
            if (string.IsNullOrWhiteSpace(UserId))
            {
                throw new PropertyNotSetException("UserId");
            }
            HttpQueryString query = new HttpQueryString();

            query.Add("method", "flickr.photosets.getList");
            query.Add("user_id", UserId);
            if (Page > 0)
            {
                query.Add("page", Page);
            }
            if (PerPage > 0)
            {
                query.Add("per_page", PerPage);
            }
            return(query);
        }
示例#30
0
        /// <summary>
        /// Gets an instance of <see cref="IHttpQueryString"/> representing the GET parameters.
        /// </summary>
        /// <returns>An instance of <see cref="IHttpQueryString"/>.</returns>
        public IHttpQueryString GetQueryString()
        {
            IHttpQueryString query = new HttpQueryString();

            query.Set("q", Query);
            if (Page > 1)
            {
                query.Set("page", Page);
            }
            if (Count != 20)
            {
                query.Set("count", Count);
            }
            if (!IncludeEntities)
            {
                query.Set("include_entities", "false");
            }

            return(query);
        }
示例#31
0
        public void GetProductsWithQueryStringRelative()
        {
            var serializer = new XmlSerializer(typeof(Crawler.Model.LinkShare.result));

            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://feed.linksynergy.com");

            HttpQueryString query = new HttpQueryString();
            query.Add("token", "5bfb339580a02308573204c2ac1bb921ecba09ba542a19d271c2d7e9c27a509f");
            query.Add("keyword", "DVD Player");
            query.Add("Page", "1");
            query.Add("MaxResults", "100");

            var uri = HttpQueryString.MakeQueryString(new Uri("/productsearch?", UriKind.Relative), query);
            var req = new HttpRequestMessage("GET", uri);

            using (var response = client.Send(req))
            {
                //string results = response.Content.ReadAsString();
                var extended = (object)serializer.Deserialize(response.Content.ReadAsStream());
            }
        }
        public void GetProductsWithQueryStringRelative()
        {
            var serializer = new XmlSerializer(typeof(Crawler.Model.CJ.cjapi));

            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("https://product-search.api.cj.com");

            HttpQueryString query = new HttpQueryString();
            query.Add("website-id", "3100204");
            query.Add("keywords", "DVD");
            query.Add("page-number", "1");
            query.Add("records-per-page", "1000");

            var uri = HttpQueryString.MakeQueryString(new Uri("/v2/product-search?", UriKind.Relative), query);
            var req = new HttpRequestMessage("GET", uri);
            req.Headers.Add("authorization", "00b171e48c4bc1e70836b252e1c4c40a893f19db0457be8447b1acdbdc0e7e769e1b804c1af54f883326d6147d1365f4b5f031a61740cf0c63a9f4b3d174cebbbf/420a385c3aa9bcd962b9f57ccf2583225758c11999aa6f42db8e90f9126fe0a7110790cd2ccd66a4f1861e89bd33fcfa6f528b494fa183f5d380ca289d18c309");

            using (var response = client.Send(req))
            {
                //string results = response.Content.ReadAsString();
                var extended = (object)serializer.Deserialize(response.Content.ReadAsStream());
            }
        }
示例#33
0
        /// <summary>
        /// 判断当前登录用户是否是黄钻。
        /// </summary>
        /// <param name="openId">登录用户的OpenID。</param>
        /// <param name="openKey">登录用户的OpenKey。</param>
        /// <returns></returns>
        public bool IsVip(string openId, string openKey)
        {
            var path = "/pay/is_vip";

            var query = new HttpQueryString()
                .Append("openid", openId)
                .Append("openkey", openKey)
                .Append("appid", this.AppId.ToString())
                .Append("appkey", this.AppKey)
                .Append("appname", this.AppName);

            var json = RestApiClient.Get(path, query).Ensure().ReadJsonContent() as JObject;

            return bool.Parse(json["is_vip"].ToString());
        }
示例#34
0
        /**
         * Retrieve metadata from CSP
         * includes simple caching
         */
        public Metadata getMetadata(string path, bool list=true)
        {
            path = stripLeadingSlash(path);
            if (gdocsLinkExtension && path.EndsWith(".url"))
            {
                path = path.Substring(0, path.Length-4);
            }
            // check metadata cache
            Metadata metadata = metadataCache[path];
            if (metadata != null)
            {
                System.Diagnostics.Debug.Print("MetadataCache hit! {0}", path);
                return metadata;
            }

            HttpClient http = new HttpClient(baseUri);
            HttpQueryString query = new HttpQueryString();
            if (list)
            {
                query.Add("list", list.ToString());
            }
            query.Add("oauth_token", token.access_token);
            Uri metadataUri = new Uri(string.Format("metadata/{0}", Uri.EscapeUriString(path)),UriKind.Relative);
            HttpResponseMessage resp = http.Get(metadataUri, query);
            if (resp.StatusCode == System.Net.HttpStatusCode.OK)
            {
                if (gdocsLinkExtension)
                {
                    metadata = resp.Content.ReadAsJsonDataContract<Metadata>();
                    PlaceUrlFiles(metadata);
                }
                else
                {
                    metadata = resp.Content.ReadAsJsonDataContract<Metadata>();
                }
                metadataCache[path] = metadata;
                return metadata;
            }
            else if (resp.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
                throw new NotFoundException();
            }
            else
            {
                throw new BadRequestException();
            }
        }
示例#35
0
        /**
         *  Get file content
         *  TODO: range query?
         */
        public Stream getFile(string path)
        {
            // remove leading slash
            path = stripLeadingSlash(path);

            if (gdocsLinkExtension && path.EndsWith(".url"))
            {
                path = path.Substring(0, path.Length - 4);
                Metadata metadata = metadataCache[path];
                if (metadata != null && metadata.gdocs_link!=null)
                {
                    return createUrlFileContent(metadata.gdocs_link);
                }
            }
            HttpClient http = new HttpClient(baseUri);
            HttpQueryString query = new HttpQueryString();
            query.Add("oauth_token", token.access_token);
            Uri contentUri = new Uri(string.Format("files/{0}", Uri.EscapeUriString(path)), UriKind.Relative);
            HttpResponseMessage resp = http.Get(contentUri, query);
            if (resp.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return new MemoryStream(resp.Content.ReadAsByteArray(), false);
            }
            else if (resp.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
                throw new NotFoundException();
            }
            else
            {
                throw new BadRequestException();
            }
        }
示例#36
0
        public AccessToken GetAccessToken(string verificationCode, string redirectUri)
        {
            var getAccessTokenUrl = new Uri(string.Format(CultureInfo.InvariantCulture, "{0}/oauth/access_token", UrlResources.GraphApiUrl));
            var queryString = new HttpQueryString();
            queryString.Add("client_id", this.AppId);
            queryString.Add("redirect_uri", redirectUri);
            queryString.Add("client_secret", this.AppSecret);
            queryString.Add("code", verificationCode);

            using (HttpClient client = new HttpClient())
            {
                using (var response = client.Get(getAccessTokenUrl, queryString).EnsureStatusIsSuccessful())
                {
                    var content = response.Content.ReadAsString();
                    var qs = HttpUtility.ParseQueryString(content);

                    return new AccessToken
                                {
                                    Token = qs["access_token"],
                                    Expires = qs["expires"] != null ? long.Parse(qs["expires"]) : new Nullable<long>()
                                };
                }
            }
        }
示例#37
0
        public IEnumerable<Status> GetUserStatus(string token, int count)
        {
            var userStatusGetUrl = new Uri(string.Format(CultureInfo.InvariantCulture, "{0}/me/statuses", UrlResources.GraphApiUrl));

            var queryString = new HttpQueryString();
            queryString.Add("access_token", token);
            queryString.Add("limit", count.ToString());

            using (HttpClient client = new HttpClient())
            {
                using (var response = client.Get(userStatusGetUrl, queryString).EnsureStatusIsSuccessful())
                {
                    var status = response.Content.ReadAsJsonDataContract<ArrayOfStatus>();
                    return status.UserStatuses.ToList();
                }
            }
        }
示例#38
0
        public User GetUser(string accessToken)
        {
            var userProfileUrl = new Uri(string.Format(CultureInfo.InvariantCulture, "{0}/me", UrlResources.GraphApiUrl));

            var queryString = new HttpQueryString();
            queryString.Add("access_token", accessToken);

            using (HttpClient client = new HttpClient())
            {
                using (var response = client.Get(userProfileUrl, queryString).EnsureStatusIsSuccessful())
                {
                    var userProfile = response.Content.ReadAsJsonDataContract<User>();
                    return userProfile;
                }
            }
        }
示例#39
0
文件: Google.cs 项目: Gevil/Projects
        /// <summary>
        ///     Translates the specified text.
        /// </summary>
        /// <param name="text">
        ///     The text to translate.
        /// </param>
        /// <param name="sourceLanguage">
        ///     The language to translate from.
        /// </param>
        /// <param name="destinationLanguage">
        ///     The language to translate to.
        /// </param>
        /// <param name="textFormat">
        ///     The format of the text to be translated.
        /// </param>
        /// <returns>
        ///     A response that includes the translated text and status information.
        /// </returns>
        /// <exception cref="ArgumentException">
        ///     Thrown if the text to translate or destination language is null or empty.
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        ///     Thrown if the HTTP response status code is not 200.
        /// </exception>
        /// <exception cref="ApplicationException">
        ///     Thrown if the response fails due to a non-communication related problem.
        ///     The response details returned from Google are included in the exception message.
        /// </exception>
        /// <remarks>
        ///     If the source language is not provided it will be automatically detected.
        /// </remarks>
        public static TranslationResponse Translate(string text, string sourceLanguage, string destinationLanguage, TextFormat textFormat)
        {
            if (string.IsNullOrEmpty(text)) throw new ArgumentException("The 'text' parameter is invalid.", "text");
            if (string.IsNullOrEmpty(destinationLanguage)) throw new ArgumentException("The 'destinationLanguage' parameter is invalid.", "destinationLanguage");

            HttpClient client = new HttpClient("http://ajax.googleapis.com/");

            HttpQueryString queryString = new HttpQueryString
            {
                {"v", "1.0"},
                {"hl", Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName},
                {"langpair", string.Format("{0}|{1}", sourceLanguage.ToLowerInvariant(), destinationLanguage.ToLowerInvariant())},
                {"q", text},
                {"format", textFormat.ToString().ToLower()}
            };

            Uri serviceUri = new Uri("ajax/services/language/translate", UriKind.Relative);

            HttpResponseMessage responseMessage = client.Get(serviceUri, queryString);
            responseMessage.EnsureStatusIsSuccessful();

            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(TranslationResponse));
            return (TranslationResponse)serializer.ReadObject(responseMessage.Content.ReadAsStream());
        }
        private void BuildRequest()
        {
            HttpQueryString query = new HttpQueryString();
            query.Add(Model.CJ.QueryConstants.WebsiteID, ConfigurationManager.AppSettings["cjSiteID"]);
            query.Add(Model.CJ.QueryConstants.PageNumber, "1");
            query.Add(Model.CJ.QueryConstants.RecordsPerPage, "1000");

            var uri = HttpQueryString.MakeQueryString(new Uri(METHOD, UriKind.Relative), query);
            request = new HttpRequestMessage("GET", uri);

            request.Headers.Add(Model.CJ.QueryConstants.Authorization, ConfigurationManager.AppSettings["cjDeveloperKey"]);
        }
示例#41
0
        /// <summary>
        /// 批量获取用户信息。
        /// </summary>
        /// <param name="openId">登录用户的OpenID。</param>
        /// <param name="openKey">登录用户的OpenKey。</param>
        /// <param name="fopenids">用户的OpenID列表。</param>
        /// <returns></returns>
        public IEnumerable<Models.UserInfo> GetUsers(string openId, string openKey, params string[] fopenids)
        {
            var path = "/user/multi_info";

            var query = new HttpQueryString()
                .Append("openid", openId)
                .Append("openkey", openKey)
                .Append("appid", this.AppId.ToString())
                .Append("appkey", this.AppKey)
                .Append("appname", this.AppName)
                .Append("fopenids", string.Join("_", fopenids));

            var json = RestApiClient.Get(path, query).Ensure().ReadJsonContent() as JObject;

            return JsonConvert.DeserializeObject<IEnumerable<Models.UserInfo>>(json["items"].ToString());
        }
示例#42
0
        /// <summary>
        /// 获取当前登录用户,包括用户基本资料以及黄钻级别等相关信息。
        /// </summary>
        /// <param name="openId">登录用户的OpenID。</param>
        /// <param name="openKey">登录用户的OpenKey。</param>
        /// <returns></returns>
        public Models.UserInfo GetUserInfo(string openId, string openKey)
        {
            var path = "/user/info";

            var query = new HttpQueryString()
                .Append("openid", openId)
                .Append("openkey", openKey)
                .Append("appid", this.AppId.ToString())
                .Append("appkey", this.AppKey)
                .Append("appname", this.AppName);

            return RestApiClient.Get(path, query).Ensure().ReadJsonContent<Models.UserInfo>();
        }
示例#43
0
        /// <summary>
        /// 获取好友关系链以及详细信息。
        /// </summary>
        /// <param name="openId">登录用户的OpenID。</param>
        /// <param name="openKey">登录用户的OpenKey。</param>
        /// <param name="infoed">是否需要好友的详细信息。</param>
        /// <param name="apped">是否已经安装此应用。</param>
        /// <param name="page">页码(0表示不分页)。</param>
        /// <returns></returns>
        public IEnumerable<Models.UserInfo> GetFriends(string openId, string openKey, bool infoed, bool? apped, int page)
        {
            var path = "/relation/friends";

            var query = new HttpQueryString()
                .Append("openid", openId)
                .Append("openkey", openKey)
                .Append("appid", this.AppId.ToString())
                .Append("appkey", this.AppKey)
                .Append("appname", this.AppName)
                .Append("infoed", infoed ? "1" : "0")
                .Append("apped", apped.HasValue ? (apped.Value ? "1" : "-1") : "0")
                .Append("page", page.ToString());

            var json = RestApiClient.Get(path, query).Ensure().ReadJsonContent() as JObject;

            return JsonConvert.DeserializeObject<IEnumerable<Models.UserInfo>>(json["items"].ToString());
        }
示例#44
0
        /// <summary>
        /// 验证登录用户是否安装了应用。已经安装返回true,否则返回false。
        /// </summary>
        /// <param name="openId">登录用户的OpenID。</param>
        /// <param name="openKey">登录用户的OpenKey。</param>
        /// <returns></returns>
        public bool IsSetuped(string openId, string openKey)
        {
            var path = "/user/is_setuped";

            var query = new HttpQueryString()
                .Append("openid", openId)
                .Append("openkey", openKey)
                .Append("appid", this.AppId.ToString())
                .Append("appkey", this.AppKey)
                .Append("appname", this.AppName);

            var json = RestApiClient.Get(path, query).Ensure().ReadJsonContent() as JObject;

            return json["setuped"].ToString() == "1";
        }
示例#45
0
        /// <summary>
        /// 判断登录用户与指定OpenID的用户是否为好友关系,是好友返回true,否则返回false。
        /// </summary>
        /// <param name="openId">登录用户的OpenID。</param>
        /// <param name="openKey">登录用户的OpenKey。</param>
        /// <param name="fopenid">用户的OpenID。</param>
        /// <returns></returns>
        public bool IsFriend(string openId, string openKey, string fopenid)
        {
            var path = "/relation/is_friend";

            var query = new HttpQueryString()
                .Append("openid", openId)
                .Append("openkey", openKey)
                .Append("appid", this.AppId.ToString())
                .Append("appkey", this.AppKey)
                .Append("appname", this.AppName)
                .Append("fopenid", fopenid);

            var json = RestApiClient.Get(path, query).Ensure().ReadJsonContent() as JObject;

            return int.Parse(json["isFriend"].ToString()) >= 1;
        }