using System.Collections.Specialized;
using System.IO;
using System.Net;
+using System.Net.Http;
using System.Text;
+using System.Threading;
using System;
using System.Collections.Generic;
using System.IO.Compression;
///<summary>
///プロキシ
///</summary>
- internal static WebProxy proxy = null;
+ private static IWebProxy proxy = null;
///<summary>
///ユーザーが選択したプロキシの方式
///</summary>
- internal static ProxyType proxyKind = ProxyType.IE;
+ private static ProxyType proxyKind = ProxyType.IE;
///<summary>
///初期化済みフラグ
}
#endregion
+ /// <summary>
+ /// OpenTween 内で共通して使用する HttpClient インスタンス
+ /// </summary>
+ public static HttpClient GlobalHttpClient
+ {
+ get { return globalHttpClient; }
+ }
+
+ /// <summary>
+ /// Webプロキシの設定が変更された場合に発生します
+ /// </summary>
+ public static event EventHandler WebProxyChanged;
+
+ private static HttpClient globalHttpClient = CreateHttpClient(new HttpClientHandler());
+
///<summary>
///通信クラスの初期化処理。タイムアウト値とプロキシを設定する
///</summary>
///<param name="proxyPort">プロキシのポート番号</param>
///<param name="proxyUser">プロキシ認証が必要な場合のユーザ名。不要なら空文字</param>
///<param name="proxyPassword">プロキシ認証が必要な場合のパスワード。不要なら空文字</param>
- public static void InitializeConnection(
- int timeout,
- ProxyType proxyType,
- string proxyAddress,
- int proxyPort,
- string proxyUser,
- string proxyPassword)
+ public static void InitializeConnection(int timeout,
+ ProxyType proxyType, string proxyAddress, int proxyPort,
+ string proxyUser, string proxyPassword)
{
- isInitialize = true;
+ HttpConnection.isInitialize = true;
+ HttpConnection.DefaultTimeout = timeout * 1000; // s -> ms
+
ServicePointManager.Expect100Continue = false;
- DefaultTimeout = timeout * 1000; //s -> ms
+
+ SetWebProxy(proxyType, proxyAddress, proxyPort, proxyUser, proxyPassword);
+ }
+
+ public static void SetWebProxy(ProxyType proxyType, string proxyAddress, int proxyPort,
+ string proxyUser, string proxyPassword)
+ {
+ IWebProxy proxy;
switch (proxyType)
{
case ProxyType.None:
proxy = null;
break;
case ProxyType.Specified:
- proxy = new WebProxy("http://" + proxyAddress + ":" + proxyPort);
- if (!String.IsNullOrEmpty(proxyUser) || !String.IsNullOrEmpty(proxyPassword))
+ proxy = new WebProxy(proxyAddress, proxyPort);
+ if (!string.IsNullOrEmpty(proxyUser) || !string.IsNullOrEmpty(proxyPassword))
proxy.Credentials = new NetworkCredential(proxyUser, proxyPassword);
break;
case ProxyType.IE:
- //IE設定(システム設定)はデフォルト値なので処理しない
+ default:
+ proxy = WebRequest.GetSystemWebProxy();
break;
}
- proxyKind = proxyType;
+
+ HttpConnection.proxyKind = proxyType;
+ HttpConnection.proxy = proxy;
Win32Api.SetProxy(proxyType, proxyAddress, proxyPort, proxyUser, proxyPassword);
+
+ OnWebProxyChanged(EventArgs.Empty);
+ }
+
+ /// <summary>
+ /// プロキシ等の設定を施した HttpClient インスタンスを生成します
+ /// </summary>
+ /// <remarks>
+ /// 通常は HttpConnection.GlobalHttpClient を使用すべきです。
+ /// このメソッドを使用する場合は、WebProxyChanged イベントが発生する度に HttpClient を生成し直すように実装してください。
+ /// </remarks>
+ public static HttpClient CreateHttpClient(HttpClientHandler handler)
+ {
+ if (HttpConnection.proxy != null)
+ {
+ handler.UseProxy = true;
+ handler.Proxy = HttpConnection.proxy;
+ }
+ else
+ {
+ handler.UseProxy = false;
+ }
+
+ var client = new HttpClient(handler);
+ client.Timeout = TimeSpan.FromMilliseconds(HttpConnection.DefaultTimeout);
+ client.DefaultRequestHeaders.Add("User-Agent", MyCommon.GetUserAgentString());
+
+ return client;
+ }
+
+ private static void OnWebProxyChanged(EventArgs e)
+ {
+ var newClient = HttpConnection.CreateHttpClient(new HttpClientHandler());
+ var oldClient = Interlocked.Exchange(ref globalHttpClient, newClient);
+ oldClient.Dispose();
+
+ if (WebProxyChanged != null)
+ WebProxyChanged(null, e);
}
}
}
\ No newline at end of file
content.Add(fileContent, "image", file.Name);
content.Add(titleContent, "title");
- using (var http = MyCommon.CreateHttpClient())
using (var request = new HttpRequestMessage(HttpMethod.Post, UploadEndpoint))
{
- http.Timeout = TimeSpan.FromMinutes(1);
-
request.Headers.Authorization =
new AuthenticationHeaderValue("Client-ID", ApplicationSettings.ImgurClientID);
request.Content = content;
- using (var response = await http.SendAsync(request).ConfigureAwait(false))
+ using (var response = await HttpConnection.GlobalHttpClient.SendAsync(request).ConfigureAwait(false))
{
response.EnsureSuccessStatusCode();
}
/// <summary>
- /// OpenTween 内で共通して使う設定を施した HttpClient インスタンスを作成します
- /// </summary>
- public static HttpClient CreateHttpClient()
- {
- return CreateHttpClient(new HttpClientHandler());
- }
-
- /// <summary>
- /// OpenTween 内で共通して使う設定を施した HttpClient インスタンスを作成します
- /// </summary>
- public static HttpClient CreateHttpClient(HttpClientHandler handler)
- {
- switch (HttpConnection.proxyKind)
- {
- case HttpConnection.ProxyType.None:
- handler.UseProxy = false;
- break;
- case HttpConnection.ProxyType.Specified:
- handler.UseProxy = true;
- handler.Proxy = HttpConnection.proxy;
- break;
- case HttpConnection.ProxyType.IE:
- default:
- handler.UseProxy = true;
- handler.Proxy = WebRequest.GetSystemWebProxy();
- break;
- }
-
- var client = new HttpClient(handler);
- client.DefaultRequestHeaders.Add("User-Agent", MyCommon.GetUserAgentString());
-
- return client;
- }
-
- /// <summary>
/// 指定された IDictionary を元にクエリ文字列を生成します
/// </summary>
/// <param name="param">生成するクエリの key-value コレクション</param>
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
+using System.Threading;
using System.Threading.Tasks;
using System.Web;
static ShortUrl()
{
- _instance = new Lazy<ShortUrl>(() =>
- {
- var handler = new HttpClientHandler
- {
- AllowAutoRedirect = false,
- };
-
- var http = MyCommon.CreateHttpClient(handler);
- http.Timeout = new TimeSpan(0, 0, seconds: 5);
+ _instance = new Lazy<ShortUrl>(() => new ShortUrl(), true);
+ }
- return new ShortUrl(http);
- }, true);
+ internal ShortUrl()
+ : this(CreateDefaultHttpClient())
+ {
+ HttpConnection.WebProxyChanged += (o, e) =>
+ {
+ var newClient = CreateDefaultHttpClient();
+ var oldClient = Interlocked.Exchange(ref this.http, newClient);
+ oldClient.Dispose();
+ };
}
internal ShortUrl(HttpClient http)
return response.Headers.Location;
}
}
+
+ private static HttpClient CreateDefaultHttpClient()
+ {
+ var handler = new HttpClientHandler
+ {
+ AllowAutoRedirect = false,
+ };
+
+ var http = HttpConnection.CreateHttpClient(handler);
+ http.Timeout = TimeSpan.FromSeconds(5);
+
+ return http;
+ }
}
}
public Task<MemoryImage> LoadThumbnailImageAsync(CancellationToken cancellationToken)
{
- return Task.Run(async () =>
- {
- using (var http = MyCommon.CreateHttpClient())
- {
- return await this.LoadThumbnailImageAsync(http, cancellationToken)
- .ConfigureAwait(false);
- }
- }, cancellationToken);
+ return this.LoadThumbnailImageAsync(HttpConnection.GlobalHttpClient, cancellationToken);
}
public async virtual Task<MemoryImage> LoadThumbnailImageAsync(HttpClient http, CancellationToken cancellationToken)
{
public partial class TweenMain : OTBaseForm
{
- private readonly HttpClient http;
+ private HttpClient http;
//各種設定
private Size _mySize; //画面サイズ
private HookGlobalHotkey _hookGlobalHotkey;
public TweenMain()
{
- this.http = MyCommon.CreateHttpClient();
+ this.http = HttpConnection.CreateHttpClient(new HttpClientHandler());
+ HttpConnection.WebProxyChanged += (o, e) =>
+ {
+ var newClient = HttpConnection.CreateHttpClient(new HttpClientHandler());
+ var oldClient = Interlocked.Exchange(ref this.http, newClient);
+ oldClient.Dispose();
+ };
+
_hookGlobalHotkey = new HookGlobalHotkey(this);
// この呼び出しは、Windows フォーム デザイナで必要です。
public event EventHandler<ThumbnailDoubleClickEventArgs> ThumbnailDoubleClick;
public event EventHandler<ThumbnailImageSearchEventArgs> ThumbnailImageSearchClick;
- private readonly HttpClient http = MyCommon.CreateHttpClient();
-
private object uiLockObj = new object();
public ThumbnailInfo Thumbnail
picbox.Tag = thumb;
picbox.ContextMenuStrip = this.contextMenuStrip;
- var loadTask = picbox.SetImageFromTask(() => thumb.LoadThumbnailImageAsync(this.http, cancelToken));
+ var loadTask = picbox.SetImageFromTask(() => thumb.LoadThumbnailImageAsync(cancelToken));
loadTasks.Add(loadTask);
var tooltipText = thumb.TooltipText;
await this.UserPicture.SetImageFromTask(async () =>
{
- using (var http = MyCommon.CreateHttpClient())
- {
- var imageStream = await http.GetStreamAsync(imageUri.Replace("_normal", "_bigger"))
- .ConfigureAwait(false);
+ var uri = imageUri.Replace("_normal", "_bigger");
- return await MemoryImage.CopyFromStreamAsync(imageStream)
- .ConfigureAwait(false);
- }
+ var imageStream = await HttpConnection.GlobalHttpClient.GetStreamAsync(uri)
+ .ConfigureAwait(false);
+
+ return await MemoryImage.CopyFromStreamAsync(imageStream)
+ .ConfigureAwait(false);
});
}