本文整理汇总了C#中System.Net.Http.HttpClientHandler.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# HttpClientHandler.Dispose方法的具体用法?C# HttpClientHandler.Dispose怎么用?C# HttpClientHandler.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Http.HttpClientHandler
的用法示例。
在下文中一共展示了HttpClientHandler.Dispose方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: StartUpload
public bool StartUpload(string fileName,int assetId)
{
var handler = new HttpClientHandler() { UseDefaultCredentials = true };
string url = "http://c0040597.itcs.hp.com:7860/Report/Upload";
HttpClient client = new HttpClient(handler);
MultipartFormDataContent form = new MultipartFormDataContent();
form.Add(new StringContent(assetId.ToString()), "asset");
byte[] fileContent = File.ReadAllBytes(fileName);
form.Add(new ByteArrayContent(fileContent), "file", fileName);
var task = client.PostAsync(url, form);
task.Wait();
var response = task.Result;
client.Dispose();
handler.Dispose();
if (response.IsSuccessStatusCode)
return true;
return false;
}
示例2: DeCompressionTest
public static void DeCompressionTest(string url)
{
var clientHandler = new HttpClientHandler();
clientHandler.AutomaticDecompression = DecompressionMethods.None;
//clientHandler.AutomaticDecompression = DecompressionMethods.Deflate;
clientHandler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
var httpClient = new HttpClient(clientHandler);
httpClient.MaxResponseContentBufferSize = 256000;
httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
try{
var responseTask = httpClient.GetAsync(url);
responseTask.Wait();
HttpResponseMessage response = responseTask.Result;
response.EnsureSuccessStatusCode();
if(response.Content != null) {
var readTask = response.Content.ReadAsStringAsync();
readTask.Wait();
Console.WriteLine("*****");
Console.WriteLine(readTask.Result);
}
else
{
Console.WriteLine(response.StatusCode + " " + response.ReasonPhrase + Environment.NewLine);
}
}
catch(Exception e)
{
Console.WriteLine(e);
return ;
}
finally{
Console.WriteLine("disposing");
clientHandler.Dispose();
httpClient.Dispose();
}
return;
}
示例3: InitializeHttpClient
private static HttpClient InitializeHttpClient(TimeSpan timeout)
{
HttpClient httpClient;
var httpHandler = new HttpClientHandler();
try
{
httpHandler.AllowAutoRedirect = false;
httpHandler.MaxRequestContentBufferSize = 1024;
httpHandler.UseCookies = false;
httpHandler.UseDefaultCredentials = false;
httpClient = new HttpClient(httpHandler, true);
}
catch
{
httpHandler.Dispose();
throw;
}
httpClient.DefaultRequestHeaders.UserAgent.Clear();
httpClient.DefaultRequestHeaders.UserAgent.Add(GetUserAgent());
httpClient.Timeout = timeout;
httpClient.MaxResponseContentBufferSize = 1024;
return httpClient;
}
示例4: MultipartUpload
public async Task<MultipartUploadResult> MultipartUpload(MultiUploadRequestData multiUploadObject,
Action<HttpProcessData> uploadProcessCallback = null, CancellationToken? cancellationToken = null)
{
MultipartUploadResult result = null;
HttpClientHandler hand = null;
// ProgressMessageHandler processMessageHander = null;
HttpClient localHttpClient = null;
OssHttpRequestMessage httpRequestMessage = null;
HttpResponseMessage response = null;
try
{
hand = new HttpClientHandler();
// processMessageHander = new ProgressMessageHandler(hand);
localHttpClient = new HttpClient();
localHttpClient.Timeout += new TimeSpan(2 * TimeSpan.TicksPerHour);
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("partNumber", multiUploadObject.PartNumber);
parameters.Add("uploadId", multiUploadObject.UploadId);
httpRequestMessage = new OssHttpRequestMessage(multiUploadObject.Bucket, multiUploadObject.Key, parameters);
httpRequestMessage.Method = HttpMethod.Put;
httpRequestMessage.Headers.Date = DateTime.UtcNow;
httpRequestMessage.Content = new StreamContent(multiUploadObject.Content);
//if (uploadProcessCallback != null)
//{
// processMessageHander.HttpSendProgress += (sender, e) =>
// {
// uploadProcessCallback(new HttpProcessData()
// {
// TotalBytes = e.TotalBytes,
// BytesTransferred = e.BytesTransferred,
// ProgressPercentage = e.ProgressPercentage
// });
// };
//}
OssRequestSigner.Sign(httpRequestMessage, networkCredential);
if (cancellationToken != null)
response = await localHttpClient.SendAsync(httpRequestMessage, (CancellationToken)cancellationToken);
else
response = await localHttpClient.SendAsync(httpRequestMessage);
if (response.IsSuccessStatusCode == false)
{
await ErrorResponseHandler.Handle(response);
}
var deseserializer = DeserializerFactory.GetFactory().CreateMultipartUploadDeserializer();
result = deseserializer.Deserialize(response);
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (hand != null)
hand.Dispose();
//if (processMessageHander != null)
// processMessageHander.Dispose();
if (localHttpClient != null)
localHttpClient.Dispose();
if (httpRequestMessage != null)
httpRequestMessage.Dispose();
if (response != null)
response.Dispose();
}
return result;
}
示例5: GetObject
public async Task<OssObject> GetObject(GetObjectRequest getObjectRequest,
Action<HttpProcessData> downloadProcessCallback = null, CancellationToken? cancellationToken = null)
{
OssObject result = null;
HttpClientHandler hand = null;
// ProgressMessageHandler processMessageHander = null;
HttpClient localHttpClient = null;
OssHttpRequestMessage httpRequestMessage = null;
HttpResponseMessage response = null;
try
{
hand = new HttpClientHandler();
// processMessageHander = new ProgressMessageHandler(hand);
localHttpClient = new HttpClient();
localHttpClient.Timeout += new TimeSpan(2 * TimeSpan.TicksPerHour);
httpRequestMessage = new OssHttpRequestMessage(getObjectRequest.BucketName, getObjectRequest.Key);
getObjectRequest.ResponseHeaders.Populate(httpRequestMessage.Headers);
getObjectRequest.Populate(httpRequestMessage.Headers);
httpRequestMessage.Method = HttpMethod.Get;
httpRequestMessage.Headers.Date = DateTime.UtcNow;
OssRequestSigner.Sign(httpRequestMessage, networkCredential);
//if (downloadProcessCallback != null)
//{
// processMessageHander.HttpReceiveProgress += (sender, e) =>
// {
// downloadProcessCallback(new HttpProcessData()
// {
// TotalBytes = e.TotalBytes,
// BytesTransferred = e.BytesTransferred,
// ProgressPercentage = e.ProgressPercentage
// }); ;
// };
//}
if (cancellationToken != null)
response = await localHttpClient.SendAsync(httpRequestMessage, (CancellationToken)cancellationToken);
else
response = await localHttpClient.SendAsync(httpRequestMessage);
if (response.IsSuccessStatusCode == false)
{
await ErrorResponseHandler.Handle(response);
}
var temp = DeserializerFactory.GetFactory().CreateGetObjectResultDeserializer(getObjectRequest);
result = await temp.Deserialize(response);
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (hand != null)
hand.Dispose();
//if (processMessageHander != null)
// processMessageHander.Dispose();
if (localHttpClient != null)
localHttpClient.Dispose();
if (httpRequestMessage != null)
httpRequestMessage.Dispose();
}
return result;
}
示例6: PutObject
public async Task<PutObjectResult> PutObject(string bucketName, string key, Stream content, ObjectMetadata metadata,
Action<HttpProcessData> uploadProcessCallback = null, CancellationToken? cancellationToken = null)
{
PutObjectResult result = null;
HttpClientHandler hand = null;
// ProgressMessageHandler processMessageHander = null;
HttpClient localHttpClient = null;
OssHttpRequestMessage httpRequestMessage = null;
HttpResponseMessage response = null;
try
{
hand = new HttpClientHandler();
// processMessageHander = new ProgressMessageHandler(hand);
localHttpClient = new HttpClient();
localHttpClient.Timeout += new TimeSpan(2 * TimeSpan.TicksPerHour);
httpRequestMessage = new OssHttpRequestMessage(bucketName, key);
httpRequestMessage.Method = HttpMethod.Put;
httpRequestMessage.Headers.Date = DateTime.UtcNow;
httpRequestMessage.Content = new StreamContent(content);
OssClientHelper.initialHttpRequestMessage(httpRequestMessage, metadata);
OssRequestSigner.Sign(httpRequestMessage, networkCredential);
//if (uploadProcessCallback != null)
//{
// processMessageHander.HttpSendProgress += (sender, e) =>
// {
// uploadProcessCallback(new HttpProcessData()
// {
// TotalBytes = e.TotalBytes,
// BytesTransferred = e.BytesTransferred,
// ProgressPercentage = e.ProgressPercentage
// });
// };
//}
if(cancellationToken != null)
response = await localHttpClient.SendAsync(httpRequestMessage, (CancellationToken)cancellationToken);
else
response = await localHttpClient.SendAsync(httpRequestMessage);
if (response.IsSuccessStatusCode == false)
{
await ErrorResponseHandler.Handle(response);
}
var temp = DeserializerFactory.GetFactory().CreatePutObjectReusltDeserializer();
result = temp.Deserialize(response);
//localHttpClient.Dispose();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (hand != null)
hand.Dispose();
//if (processMessageHander != null)
// processMessageHander.Dispose();
if (localHttpClient != null)
localHttpClient.Dispose();
if (httpRequestMessage != null)
httpRequestMessage.Dispose();
if (response != null)
response.Dispose();
}
return result;
}
示例7: GetDefaultClient
private static HttpClient GetDefaultClient()
{
if (s_DefaultHttpClient == null)
{
var handler = new System.Net.Http.HttpClientHandler();
try
{
if (handler.SupportsAutomaticDecompression)
handler.AutomaticDecompression = System.Net.DecompressionMethods.Deflate | System.Net.DecompressionMethods.GZip;
s_DefaultHttpClient = new HttpClient(handler);
}
catch
{
if (handler != null)
handler.Dispose();
throw;
}
}
return s_DefaultHttpClient;
}
示例8: Disposed
public void Disposed ()
{
var h = new HttpClientHandler ();
h.Dispose ();
var c = new HttpClient (h);
try {
c.GetAsync ("http://google.com").Wait ();
Assert.Fail ("#1");
} catch (AggregateException e) {
Assert.IsTrue (e.InnerException is ObjectDisposedException, "#2");
}
}
示例9: Speak
/// <summary>
/// Sends the specified text to be spoken to the TTS service and saves the response audio to a file.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A Task</returns>
public Task Speak(CancellationToken cancellationToken)
{
var cookieContainer = new CookieContainer();
var handler = new HttpClientHandler() { CookieContainer = cookieContainer };
var client = new HttpClient(handler);
foreach (var header in this.inputOptions.Headers)
{
client.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value);
}
var genderValue = "";
switch (this.inputOptions.VoiceType)
{
case Gender.Male:
genderValue = "Male";
break;
case Gender.Female:
default:
genderValue = "Female";
break;
}
var request = new HttpRequestMessage(HttpMethod.Post, this.inputOptions.RequestUri)
{
Content = new StringContent(String.Format(SsmlTemplate, this.inputOptions.Locale, genderValue, this.inputOptions.VoiceName, this.inputOptions.Text))
};
var httpTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
Console.WriteLine("Response status code: [{0}]", httpTask.Result.StatusCode);
var saveTask = httpTask.ContinueWith(
async (responseMessage, token) =>
{
try
{
if (responseMessage.IsCompleted && responseMessage.Result != null && responseMessage.Result.IsSuccessStatusCode)
{
var httpStream = await responseMessage.Result.Content.ReadAsStreamAsync().ConfigureAwait(false);
this.AudioAvailable(new GenericEventArgs<Stream>(httpStream));
}
else
{
this.Error(new GenericEventArgs<Exception>(new Exception(String.Format("Service returned {0}", responseMessage.Result.StatusCode))));
}
}
catch (Exception e)
{
this.Error(new GenericEventArgs<Exception>(e.GetBaseException()));
}
finally
{
responseMessage.Dispose();
request.Dispose();
client.Dispose();
handler.Dispose();
}
},
TaskContinuationOptions.AttachedToParent,
cancellationToken);
return saveTask;
}
示例10: DoProxyForUrl
public static void DoProxyForUrl(string url)
{
var proxy = new MyProxyImpl("http://localhost:8394");
var credential = new System.Net.NetworkCredential("skapila","blah","FAREAST");
credential.UserName = "skapila";
credential.Password = "blah";
credential.Domain = "FAREAST";
proxy.Credentials = credential;
var clientHandler = new HttpClientHandler();
clientHandler.Proxy = proxy;
clientHandler.UseProxy = true;
var httpClient = new HttpClient(clientHandler);
httpClient.MaxResponseContentBufferSize = 256000;
httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
try{
var responseTask = httpClient.GetAsync(url);
responseTask.Wait();
HttpResponseMessage response = responseTask.Result;
// response.EnsureSuccessStatusCode();
if(response.Content != null) {
var readTask = response.Content.ReadAsStringAsync();
readTask.Wait();
Console.WriteLine(readTask.Result);
}
else
{
Console.WriteLine(response.StatusCode + " " + response.ReasonPhrase + Environment.NewLine);
}
}
catch(Exception e)
{
Console.WriteLine(e);
}
finally
{
Console.WriteLine("disposing");
clientHandler.Dispose();
httpClient.Dispose();
}
}