本文整理汇总了C#中HttpCompletionOption类的典型用法代码示例。如果您正苦于以下问题:C# HttpCompletionOption类的具体用法?C# HttpCompletionOption怎么用?C# HttpCompletionOption使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
HttpCompletionOption类属于命名空间,在下文中一共展示了HttpCompletionOption类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SendAsync
/// <summary>
/// Send request async.
/// </summary>
/// <param name="requestMessage">
/// The request message.
/// </param>
/// <param name="completionOption">
/// The completion option.
/// </param>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
protected async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage requestMessage,
HttpCompletionOption completionOption = HttpCompletionOption.ResponseHeadersRead)
{
Debug.Assert(this.Logger != null, "this.Logger != null");
Debug.Assert(this.HttpClient != null, "this.Logger != null");
try
{
if (this.Logger.IsDebugEnabled)
{
this.Logger.Debug("Send request ({0}): {1}.", requestMessage.Method, requestMessage.RequestUri);
}
HttpResponseMessage responseMessage = await this.HttpClient.SendAsync(requestMessage, completionOption);
if (this.Logger.IsDebugEnabled)
{
await this.Logger.LogResponseAsync(requestMessage.RequestUri.ToString(), responseMessage);
}
return responseMessage;
}
catch (Exception exception)
{
this.Logger.Error(exception, "Exception while sending request, Method: {0}, Uri: {1}.", requestMessage.Method, requestMessage.RequestUri);
throw;
}
}
示例2: SingleClient_ManyGets_Async
public async Task SingleClient_ManyGets_Async(int numRequests, int dop, HttpCompletionOption completionOption)
{
string responseText = CreateResponse("abcdefghijklmnopqrstuvwxyz");
using (var client = new HttpClient())
{
await ForCountAsync(numRequests, dop, i => CreateServerAndGetAsync(client, completionOption, responseText));
}
}
示例3: sendHttpAsync
private Task<HttpResponseMessage> sendHttpAsync(HttpClient client, HttpRequestMessage message, HttpCompletionOption completionOption, CancellationToken cancelationToken)
{
if (customMessageFunc == null)
{
customMessageFunc = buildHttpResponseMessage;
}
var task = Task.Run(customMessageFunc);
return task;
}
示例4: MaximumRetryAttemptedException
/// <summary>
/// Custom implementation of the IHttpProvider.SendAsync method to handle retry logic
/// </summary>
/// <param name="request">The HTTP Request Message</param>
/// <param name="completionOption">The completion option</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns>The result of the asynchronous request</returns>
/// <remarks>See here for further details: https://graph.microsoft.io/en-us/docs/overview/errors</remarks>
Task<HttpResponseMessage> IHttpProvider.SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
{
Task<HttpResponseMessage> result = null;
// Retry logic variables
int retryAttempts = 0;
int backoffInterval = this._delay;
// Loop until we need to retry
while (retryAttempts < this._retryCount)
{
try
{
// Make the request
result = base.SendAsync(request, completionOption, cancellationToken);
// And return the response in case of success
return (result);
}
// Or handle any ServiceException
catch (ServiceException ex)
{
// Check if the is an InnerException
if (ex.InnerException != null)
{
// And if it is a WebException
var wex = ex.InnerException as WebException;
if (wex != null)
{
var response = wex.Response as HttpWebResponse;
// Check if request was throttled - http status code 429
// Check is request failed due to server unavailable - http status code 503
if (response != null && (response.StatusCode == (HttpStatusCode)429 || response.StatusCode == (HttpStatusCode)503))
{
Log.Warning(Constants.LOGGING_SOURCE, CoreResources.GraphExtensions_SendAsyncRetry, backoffInterval);
//Add delay for retry
Thread.Sleep(backoffInterval);
//Add to retry count and increase delay.
retryAttempts++;
backoffInterval = backoffInterval * 2;
}
else
{
Log.Error(Constants.LOGGING_SOURCE, CoreResources.GraphExtensions_SendAsyncRetryException, wex.ToString());
throw;
}
}
}
throw;
}
}
throw new MaximumRetryAttemptedException(string.Format("Maximum retry attempts {0}, has be attempted.", this._retryCount));
}
示例5: SendAsync
/// <summary>
/// Creates and asynchronously sends an HttpRequestMethod, disposing HttpClient if AutoDispose it true.
/// Mainly used to implement higher-level extension methods (GetJsonAsync, etc).
/// </summary>
/// <returns>A Task whose result is the received HttpResponseMessage.</returns>
public async Task<HttpResponseMessage> SendAsync(HttpMethod verb, HttpContent content = null, CancellationToken? cancellationToken = null, HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead) {
try {
var request = new HttpRequestMessage(verb, this.Url) { Content = content };
request.SetFlurlSettings(this.Settings);
return await HttpClient.SendAsync(request, completionOption, cancellationToken ?? CancellationToken.None);
}
finally {
if (AutoDispose) Dispose();
}
}
示例6: ManyClients_ManyGets
public void ManyClients_ManyGets(int numRequests, int dop, HttpCompletionOption completionOption)
{
string responseText = CreateResponse("abcdefghijklmnopqrstuvwxyz");
Parallel.For(0, numRequests, new ParallelOptions { MaxDegreeOfParallelism = dop, TaskScheduler = new ThreadPerTaskScheduler() }, _ =>
{
using (var client = new HttpClient())
{
CreateServerAndGet(client, completionOption, responseText);
}
});
}
示例7: SendAsync
/// <summary>
/// Creates and asynchronously sends an HttpRequestMethod, disposing HttpClient if AutoDispose it true.
/// Mainly used to implement higher-level extension methods (GetJsonAsync, etc).
/// </summary>
/// <returns>A Task whose result is the received HttpResponseMessage.</returns>
public async Task<HttpResponseMessage> SendAsync(HttpMethod verb, HttpContent content = null, CancellationToken? cancellationToken = null, HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead) {
try {
var request = new HttpRequestMessage(verb, this.Url) { Content = content };
// mechanism for passing ad-hoc data to the MessageHandler
request.Properties.Add("AllowedHttpStatusRanges", AllowedHttpStatusRanges);
return await HttpClient.SendAsync(request, completionOption, cancellationToken ?? CancellationToken.None);
}
finally {
if (AutoDispose) Dispose();
}
}
示例8: SendAsync
public static async Task<HttpResponseMessage> SendAsync(this HttpClient httpClient, HttpRequestMessage request,
HttpCompletionOption completionOption, CancellationToken cancellationToken,
Uri referrer, long? fromBytes, long? toBytes)
{
if (null != referrer)
request.Headers.Referer = referrer;
if (null != fromBytes || null != toBytes)
request.Headers["Range"] = new RangeHeaderValue(fromBytes, toBytes).ToString();
return await SendRequestAsync(httpClient, request, completionOption, cancellationToken);
}
示例9: SendAsync
public static async Task<HttpResponseMessage> SendAsync(this HttpClient httpClient, HttpRequestMessage request,
HttpCompletionOption completionOption, CancellationToken cancellationToken,
Uri referrer, long? fromBytes, long? toBytes)
{
if (null != referrer)
request.Headers.Referrer = referrer;
if (null != fromBytes || null != toBytes)
request.Headers.Range = new RangeHeaderValue(fromBytes, toBytes);
return await httpClient.SendAsync(request, completionOption, cancellationToken).ConfigureAwait(false);
}
示例10: SendAsync
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption)
{
//client.FollowRedirections = followRedirections;
//try
//{
return client.SendAsync(request, completionOption);
//}
//finally
//{
// client.FollowRedirections = true;
//}
}
示例11: GetAsync
public static async Task<HttpResponseMessage> GetAsync(this HttpClient httpClient, Uri uri,
HttpCompletionOption completionOption, CancellationToken cancellationToken)
{
try
{
return await httpClient.GetAsync(uri, completionOption).AsTask(cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
HttpClientExceptionTranslator.ThrowBetterHttpClientException(ex, cancellationToken);
throw;
}
}
示例12: ExecuteAsync
public static async Task<HttpResponseMessage> ExecuteAsync(this Uri uri, HttpMethod method,
HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead, double timeout = 100.0)
{
try
{
using (var client = new HttpClient())
{
client.Timeout = TimeSpan.FromSeconds(timeout);
return await client.SendAsync(new HttpRequestMessage(method, uri), completionOption);
}
}
catch
{
return null;
}
}
示例13: SendAsync
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage message, HttpCompletionOption option, CancellationToken token)
{
#if NET_3_5
if(_connectionCount >= _connectionLimit) {
return Task.Delay(500).ContinueWith(t => SendAsync(message, option, token)).Unwrap();
}
Interlocked.Increment(ref _connectionCount);
#else
return _sendSemaphore?.WaitAsync()?.ContinueWith(t =>
{
#endif
var challengeResponseAuth = Authenticator as IChallengeResponseAuthenticator;
if (challengeResponseAuth != null) {
_authHandler.Borrow(x => x.Authenticator = challengeResponseAuth);
challengeResponseAuth.PrepareWithRequest(message);
}
var httpClient = default(HttpClient);
if(!_httpClient.AcquireTemp(out httpClient)) {
return null;
}
(Authenticator as ICustomHeadersAuthorizer)?.AuthorizeRequest(message);
return httpClient.SendAsync(message, option, token);
#if !NET_3_5
})?.Unwrap()?.ContinueWith(t =>
{
_sendSemaphore?.Release();
if(t.IsFaulted) {
var e = t.Exception;
if(Misc.UnwrapAggregate(e) is ObjectDisposedException) {
return null;
}
throw e;
}
return t.Result;
});
#endif
}
示例14: SendAsync
public virtual async Task<HttpResponseMessage> SendAsync(HttpRequest httpRequest, HttpCompletionOption completionOption, CancellationToken cancellationToken)
{
ThrowIfDisposed();
OnBeforeSend(httpRequest);
using (var message = CreateHttpRequestMessage(httpRequest))
{
var response = await HttpClient.SendAsync(message, completionOption, cancellationToken).ForAwait();
if (ShouldFollowResponse(response))
{
using (var followMessage = CreateHttpRequestMessage(httpRequest))
{
followMessage.RequestUri = response.Headers.Location;
return await HttpClient.SendAsync(followMessage, completionOption, cancellationToken).ForAwait();
}
}
OnAfterSend(response);
return response;
}
}
示例15: SendAsyncWorker
async Task<HttpResponseMessage> SendAsyncWorker (HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
{
using (var lcts = CancellationTokenSource.CreateLinkedTokenSource (cts.Token, cancellationToken)) {
lcts.CancelAfter (timeout);
var task = base.SendAsync (request, lcts.Token);
if (task == null)
throw new InvalidOperationException ("Handler failed to return a value");
var response = await task.ConfigureAwait (false);
if (response == null)
throw new InvalidOperationException ("Handler failed to return a response");
//
// Read the content when default HttpCompletionOption.ResponseContentRead is set
//
if (response.Content != null && (completionOption & HttpCompletionOption.ResponseHeadersRead) == 0) {
await response.Content.LoadIntoBufferAsync (MaxResponseContentBufferSize).ConfigureAwait (false);
}
return response;
}
}