Set proxy for Google.Apis.YouTube.v3

2019-03-04 16:41发布

I have the following bit of code to make a call to the

YouTubeService service = new YouTubeService(new BaseClientService.Initializer()
{
    ApiKey = AppSettings.Variables.YouTube_APIKey,
    ApplicationName = AppSettings.Variables.YouTube_AppName
});

Google.Apis.YouTube.v3.VideosResource.ListRequest request = service.Videos.List("snippet,statistics");
request.Id = string.Join(",", videoIDs);
VideoListResponse response = request.Execute();

This all works but when we deploy it to our live server, it needs to get through a proxy so we put the following into the web.config:

    <defaultProxy useDefaultCredentials="false" enabled="true">
        <proxy usesystemdefault="False" proxyaddress="http://192.111.111.102:8081" />
    </defaultProxy>

However, this doesn't seem to be working as when the call is made, I get the following error:

System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 216.58.213.74:443

Is there a way to manually set the proxy in code?

Something along the lines of:

WebProxy proxy = new WebProxy("192.111.111.102", 8081);
proxy.Credentials = new NetworkCredential(AppSettings.Variables.ProxyUser, AppSettings.Variables.ProxyPassword, AppSettings.Variables.ProxyDomain);

// apply this to the service or request object here

1条回答
迷人小祖宗
2楼-- · 2019-03-04 17:03

To get around this I had to make a webrequest to the url and map the result back to the VideoListResponse object:

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: ");
}
查看更多
登录 后发表回答