PowerToys/Wox.Infrastructure/Http/Http.cs

74 lines
2.5 KiB
C#
Raw Normal View History

using System.IO;
2014-12-21 22:03:03 +08:00
using System.Net;
using System.Text;
using System.Threading.Tasks;
using JetBrains.Annotations;
2014-12-21 22:03:03 +08:00
using Wox.Plugin;
namespace Wox.Infrastructure.Http
{
public static class Http
2014-12-21 22:03:03 +08:00
{
2016-05-14 06:28:17 +08:00
public static IWebProxy WebProxy(IHttpProxy proxy)
2014-12-21 22:03:03 +08:00
{
if (proxy != null && proxy.Enabled && !string.IsNullOrEmpty(proxy.Server))
{
if (string.IsNullOrEmpty(proxy.UserName) || string.IsNullOrEmpty(proxy.Password))
{
var webProxy = new WebProxy(proxy.Server, proxy.Port);
return webProxy;
2014-12-21 22:03:03 +08:00
}
else
2014-12-21 22:03:03 +08:00
{
var webProxy = new WebProxy(proxy.Server, proxy.Port)
{
Credentials = new NetworkCredential(proxy.UserName, proxy.Password)
};
return webProxy;
}
}
else
{
2016-05-14 06:28:17 +08:00
return WebRequest.GetSystemWebProxy();
2014-12-21 22:03:03 +08:00
}
2015-02-01 22:46:56 +08:00
}
/// <exception cref="WebException">Can't download file </exception>
public static void Download([NotNull] string url, [NotNull] string filePath, IHttpProxy proxy)
{
var client = new WebClient { Proxy = WebProxy(proxy) };
client.DownloadFile(url, filePath);
}
/// <exception cref="WebException">Can't get response from http get </exception>
public static async Task<string> Get([NotNull] string url, IHttpProxy proxy, string encoding = "UTF-8")
2015-02-01 22:46:56 +08:00
{
HttpWebRequest request = WebRequest.CreateHttp(url);
2015-02-01 22:46:56 +08:00
request.Method = "GET";
request.Timeout = 10 * 1000;
2016-05-10 06:51:10 +08:00
request.Proxy = WebProxy(proxy);
request.UserAgent = @"Mozilla/5.0 (Trident/7.0; rv:11.0) like Gecko";
var response = await request.GetResponseAsync() as HttpWebResponse;
if (response != null)
2015-01-11 21:52:30 +08:00
{
var stream = response.GetResponseStream();
if (stream != null)
2015-01-11 21:52:30 +08:00
{
using (var reader = new StreamReader(stream, Encoding.GetEncoding(encoding)))
2015-01-11 21:52:30 +08:00
{
return await reader.ReadToEndAsync();
}
2015-01-11 21:52:30 +08:00
}
else
2015-01-11 21:52:30 +08:00
{
return string.Empty;
2015-01-11 21:52:30 +08:00
}
}
else
2015-01-11 21:52:30 +08:00
{
2014-12-21 22:03:03 +08:00
return string.Empty;
}
}
}
}