2016-08-24 42 views
1

我正在研究基於.NET的Youtube API客戶端,它具有一些簡單的功能。我去創造這樣的服務實例:YouTube .NET API v3自定義HttpClient

youtubeService = new YouTubeService(new BaseClientService.Initializer() 
{ 
    ApiKey = "", 
    ApplicationName = "my_wonderful_client" 
}); 

不過,我也需要它能夠使用代理服務器進行連接,所以我去上這樣的:

if (useProxy) 
     { 
      Google.Apis.Http.ConfigurableHttpClient customClient = null; 

      string proxyUri = "http://proxy.proxy.com"; 
      NetworkCredential proxyCreds = new NetworkCredential(
       @"domain\user", 
       "pass123" 
      ); 
      WebProxy proxy = new WebProxy(proxyUri, 8080) 
      { 
       UseDefaultCredentials = false, 
       Credentials = proxyCreds, 
      }; 


      HttpClientHandler httpClientHandler = new HttpClientHandler() 
      { 
       Proxy = proxy, 
       PreAuthenticate = true, 
       UseDefaultCredentials = false, 
      }; 

      Google.Apis.Http.ConfigurableMessageHandler customHandler = new Google.Apis.Http.ConfigurableMessageHandler(httpClientHandler); 
      customClient = new Google.Apis.Http.ConfigurableHttpClient(customHandler); 
     } 

現在怎麼辦我使用我的customClient來初始化連接?唉,.NET API的文檔相當缺乏。

謝謝。

+0

Abielita,謝謝你的回答。不幸的是,第一種方法與舊版API相關,而第二種解決方案與使用API​​的原始HTTP/JSON通信沒有太大區別,無需使用任何庫。我相信,在這個框架中必須有一個簡單的解決方案,就像這個一樣詳盡。 – noisefield

回答

0

我檢查了這個related SO question關於如何通過代理服務器使用API​​。下面是示例代碼:

YouTubeRequest request = new YouTubeRequest(settings); 
GDataRequestFactory f = (GDataRequestFactory) request.Service.RequestFactory; 
IWebProxy iProxy = WebRequest.DefaultWebProxy; 
WebProxy myProxy = new WebProxy(iProxy.GetProxy(query.Uri)); 
// potentially, setup credentials on the proxy here 
myProxy.Credentials = CredentialsCache.DefaultCredentials; 
myProxy.UseDefaultCredentials = true; 
f.Proxy = myProxy; 

thread還建議做出的WebRequest的URL和結果映射回VideoListResponse對象:

try 
{ 
    Uri api = new Uri(string.Format("https://www.googleapis.com/youtube/v3/videos?id={0}&key={1}&part=snippet,statistics", videoIds, AppSettings.Variables.YouTube_APIKey)); 
    WebRequest request = WebRequest.Create(api); 

    WebProxy proxy = new WebProxy(AppSettings.Variables.ProxyAddress, AppSettings.Variables.ProxyPort); 
    proxy.Credentials = new NetworkCredential(AppSettings.Variables.ProxyUsername, AppSettings.Variables.ProxyPassword, AppSettings.Variables.ProxyDomain); 
    request.Proxy = proxy; 

    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) 
    { 
     using (StreamReader streamReader = new StreamReader(response.GetResponseStream())) 
     { 
      return JsonConvert.DeserializeObject<VideoListResponse>(streamReader.ReadToEnd()); 
     } 
    } 
} 
catch (Exception ex) 
{ 
    ErrorLog.LogError(ex, "Video entity processing error: "); 
} 

您也可以檢查此Google documentation如何在.NET客戶端庫中使用HTTP代理。