PowerToys/Wox.Infrastructure/Http/HttpRequest.cs

79 lines
2.4 KiB
C#
Raw Normal View History

using System;
using System.IO;
2014-12-21 22:03:03 +08:00
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
2014-12-21 22:03:03 +08:00
using System.Text;
using System.Threading.Tasks;
using JetBrains.Annotations;
2016-01-07 05:34:42 +08:00
using Wox.Infrastructure.Logger;
2014-12-21 22:03:03 +08:00
using Wox.Plugin;
namespace Wox.Infrastructure.Http
{
public static class HttpRequest
2014-12-21 22:03:03 +08:00
{
2016-05-10 06:51:10 +08:00
public static WebProxy 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
{
return null;
2014-12-21 22:03:03 +08:00
}
2015-02-01 22:46:56 +08:00
}
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";
HttpWebResponse response;
2014-12-21 22:03:03 +08:00
try
{
response = await request.GetResponseAsync() as HttpWebResponse;
2014-12-21 22:03:03 +08:00
}
catch (WebException e)
2014-12-21 22:03:03 +08:00
{
2016-01-07 05:34:42 +08:00
Log.Error(e);
2015-01-11 21:52:30 +08:00
return string.Empty;
}
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;
}
}
}
}