4

URL Shortener API の C#.NET で Google のサービス アカウント OAuth2 のサンプル コードを見つけるために、すでに 1 日を無駄にしています。

サーバーからサーバーへのリクエストで短縮APIを使用しようとしています。

私を助けてください。

ありがとう

4

4 に答える 4

7

Json.Netライブラリを使用する(ここから API キーを取得できます)

string longURL="http://www.google.com";

string url = "https://www.googleapis.com/urlshortener/v1/url?key=" + apiKey;
WebClient client = new WebClient();
client.Headers["Content-Type"] = "application/json";
var response = client.UploadString(url,JsonConvert.SerializeObject(new { longUrl = longURL }));

var shortUrl = (string)JObject.Parse(response)["id"];
于 2013-09-09T15:55:35.963 に答える
0

Windows 8でHttpClientを使用して動作させました。コードは次のとおりです。Api キーは必要ありません。

 var serializedUrl = JsonConvert.SerializeObject(new { longUrl = yourlongUrl});
        HttpClient client = new HttpClient();
        var Content = new StringContent(serializedUrl, Encoding.UTF8, "application/json");
        var resp = await client.PostAsync("https://www.googleapis.com/urlshortener/v1/url", Content);
        var content = await resp.Content.ReadAsStringAsync();
        var jsonObject = JsonConvert.DeserializeObject<JObject>(content);
        var shortedUrl = jsonObject["id"].Value<string>();
于 2014-02-28T16:11:43.093 に答える
0

これが私のために働いたコードです。このコードは、サーバー間接続を確立し、認証トークンを取得します。次に、URL を短縮するための呼び出しを行います。API キーは app.config に保存されます。

ここで詳細を読むことができます: http://www.am22tech.com/google-url-shortener-api-shorten-url/

using System;
using System.Collections.Generic;
using System.Web;

using System.Configuration;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Data;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Urlshortener.v1;
using Google.Apis.Urlshortener.v1.Data;
using Google.Apis.Services;

public static string shortenURL(string urlToShorten, string webSiteBasePath)
        {
            string shortURL = string.Empty;

        try
        {
            /********************************************************************/
            string AuthenticationToken = string.Empty;
            var certificate = new X509Certificate2(webSiteBasePath + "/" + ConfigurationManager.AppSettings["IHSGoogleURlShortenerPrivateKeyName"].ToString(),
                                                   ConfigurationManager.AppSettings["IHSGoogleURlShortenerPrivateKeySecret"].ToString(),
                                                   X509KeyStorageFlags.MachineKeySet |
                                                   X509KeyStorageFlags.PersistKeySet |
                                                   X509KeyStorageFlags.Exportable);

            String serviceAccountEmail = ConfigurationManager.AppSettings["IHSGoogleURLShortenerServiceAcEmail"].ToString();

            ServiceAccountCredential credential = new ServiceAccountCredential(
               new ServiceAccountCredential.Initializer(serviceAccountEmail)
               {
                   Scopes = new[] { UrlshortenerService.Scope.Urlshortener }
               }.FromCertificate(certificate));

            if (credential.RequestAccessTokenAsync(CancellationToken.None).Result)
            {
                AuthenticationToken = credential.Token.AccessToken;
            }
            // Create the service.
            var service = new UrlshortenerService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ConfigurationManager.AppSettings["IHSGoogleURLShortnerAppName"].ToString(),
            });

            // Shorten URL
            Url toInsert = new Url { LongUrl = urlToShorten };

            toInsert = service.Url.Insert(toInsert).Execute();
            shortURL = toInsert.Id;
        }

        return (shortURL);
    }
于 2014-10-14T13:36:39.043 に答える