2016-08-24 86 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代理。