PowerToys/Wox.Infrastructure/Http/Http.cs

78 lines
2.6 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;
2016-06-19 23:18:43 +08:00
using Wox.Infrastructure.UserSettings;
2014-12-21 22:03:03 +08:00
namespace Wox.Infrastructure.Http
{
public static class Http
2014-12-21 22:03:03 +08:00
{
private const string UserAgent = @"Mozilla/5.0 (Trident/7.0; rv:11.0) like Gecko";
2016-06-19 23:18:43 +08:00
public static HttpProxy Proxy { private get; set; }
public static IWebProxy WebProxy()
2014-12-21 22:03:03 +08:00
{
2016-06-19 23:18:43 +08:00
if (Proxy != null && Proxy.Enabled && !string.IsNullOrEmpty(Proxy.Server))
2014-12-21 22:03:03 +08:00
{
2016-06-19 23:18:43 +08:00
if (string.IsNullOrEmpty(Proxy.UserName) || string.IsNullOrEmpty(Proxy.Password))
2014-12-21 22:03:03 +08:00
{
2016-06-19 23:18:43 +08:00
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
{
2016-06-19 23:18:43 +08:00
var webProxy = new WebProxy(Proxy.Server, Proxy.Port)
{
2016-06-19 23:18:43 +08:00
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>
2016-06-19 23:18:43 +08:00
public static void Download([NotNull] string url, [NotNull] string filePath)
{
2016-06-19 23:18:43 +08:00
var client = new WebClient { Proxy = WebProxy() };
client.Headers.Add("user-agent", UserAgent);
client.DownloadFile(url, filePath);
}
/// <exception cref="WebException">Can't get response from http get </exception>
2016-06-19 23:18:43 +08:00
public static async Task<string> Get([NotNull] string url, 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-06-19 23:18:43 +08:00
request.Proxy = WebProxy();
request.UserAgent = UserAgent;
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;
}
}
}
}