本文整理汇总了C#中EasyRequest类的典型用法代码示例。如果您正苦于以下问题:C# EasyRequest类的具体用法?C# EasyRequest怎么用?C# EasyRequest使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
EasyRequest类属于命名空间,在下文中一共展示了EasyRequest类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Queue
/// <summary>Queues a request for the multi handle to process.</summary>
/// <param name="request"></param>
public void Queue(EasyRequest request)
{
lock (_incomingRequests)
{
// Add the request, then initiate processing.
_incomingRequests.Enqueue(request);
EnsureWorkerIsRunning();
}
}
示例2: SetSslOptions
internal static void SetSslOptions(EasyRequest easy, ClientCertificateOption clientCertOption)
{
// Disable SSLv2/SSLv3, allow TLSv1.*
easy.SetCurlOption(Interop.Http.CURLoption.CURLOPT_SSLVERSION, (long)Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1);
IntPtr userPointer = IntPtr.Zero;
if (clientCertOption == ClientCertificateOption.Automatic)
{
ClientCertificateProvider certProvider = new ClientCertificateProvider();
userPointer = GCHandle.ToIntPtr(certProvider._gcHandle);
easy.Task.ContinueWith((_, state) => ((IDisposable)state).Dispose(),
certProvider,
CancellationToken.None,
TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default);
}
else
{
Debug.Assert(clientCertOption == ClientCertificateOption.Manual, "ClientCertificateOption is manual or automatic");
}
CURLcode answer = easy.SetSslCtxCallback(s_sslCtxCallback, userPointer);
switch (answer)
{
case CURLcode.CURLE_OK:
break;
// Curl 7.38 and prior
case CURLcode.CURLE_UNKNOWN_OPTION:
// Curl 7.39 and later
case CURLcode.CURLE_NOT_BUILT_IN:
EventSourceTrace("CURLOPT_SSL_CTX_FUNCTION not supported. Platform default HTTPS chain building in use");
if (clientCertOption == ClientCertificateOption.Automatic)
{
throw new PlatformNotSupportedException(SR.net_http_unix_invalid_client_cert_option);
}
break;
default:
ThrowIfCURLEError(answer);
break;
}
}
示例3: SetSslOptions
internal static void SetSslOptions(EasyRequest easy)
{
CURLcode answer = easy.SetSslCtxCallback(s_sslCtxCallback);
switch (answer)
{
case CURLcode.CURLE_OK:
break;
// Curl 7.38 and prior
case CURLcode.CURLE_UNKNOWN_OPTION:
// Curl 7.39 and later
case CURLcode.CURLE_NOT_BUILT_IN:
VerboseTrace("CURLOPT_SSL_CTX_FUNCTION is not supported, platform default https chain building in use");
break;
default:
ThrowIfCURLEError(answer);
break;
}
}
示例4: SetSslOptions
internal static void SetSslOptions(EasyRequest easy)
{
int answer = Interop.libcurl.curl_easy_setopt(
easy._easyHandle,
Interop.libcurl.CURLoption.CURLOPT_SSL_CTX_FUNCTION,
s_sslCtxCallback);
switch (answer)
{
case Interop.libcurl.CURLcode.CURLE_OK:
break;
case Interop.libcurl.CURLcode.CURLE_NOT_BUILT_IN:
VerboseTrace("CURLOPT_SSL_CTX_FUNCTION is not supported, platform default https chain building in use");
break;
default:
ThrowIfCURLEError(answer);
break;
}
}
示例5: SetCurlCallbacks
private static void SetCurlCallbacks(EasyRequest easy, IntPtr easyGCHandle)
{
// Add callback for processing headers
easy.SetCurlOption(CURLoption.CURLOPT_HEADERFUNCTION, s_receiveHeadersCallback);
easy.SetCurlOption(CURLoption.CURLOPT_HEADERDATA, easyGCHandle);
// If we're sending data as part of the request, add callbacks for sending request data
if (easy._requestMessage.Content != null)
{
easy.SetCurlOption(CURLoption.CURLOPT_READFUNCTION, s_sendCallback);
easy.SetCurlOption(CURLoption.CURLOPT_READDATA, easyGCHandle);
easy.SetCurlOption(CURLoption.CURLOPT_SEEKFUNCTION, s_seekCallback);
easy.SetCurlOption(CURLoption.CURLOPT_SEEKDATA, easyGCHandle);
}
// If we're expecting any data in response, add a callback for receiving body data
if (easy._requestMessage.Method != HttpMethod.Head)
{
easy.SetCurlOption(CURLoption.CURLOPT_WRITEFUNCTION, s_receiveBodyCallback);
easy.SetCurlOption(CURLoption.CURLOPT_WRITEDATA, easyGCHandle);
}
}
示例6: FinishRequest
private void FinishRequest(EasyRequest completedOperation, int messageResult)
{
VerboseTrace("messageResult: " + messageResult, easy: completedOperation);
if (completedOperation._responseMessage.StatusCode != HttpStatusCode.Unauthorized && completedOperation._handler.PreAuthenticate)
{
ulong availedAuth;
if (Interop.libcurl.curl_easy_getinfo(completedOperation._easyHandle, CURLINFO.CURLINFO_HTTPAUTH_AVAIL, out availedAuth) == CURLcode.CURLE_OK)
{
// TODO: fix locking in AddCredentialToCache
completedOperation._handler.AddCredentialToCache(
completedOperation._requestMessage.RequestUri, availedAuth, completedOperation._networkCredential);
}
// Ignore errors: no need to fail for the sake of putting the credentials into the cache
}
switch (messageResult)
{
case CURLcode.CURLE_OK:
completedOperation.EnsureResponseMessagePublished();
break;
default:
completedOperation.FailRequest(CreateHttpRequestException(new CurlException(messageResult, isMulti: false)));
break;
}
// At this point, we've completed processing the entire request, either due to error
// or due to completing the entire response.
completedOperation.Cleanup();
}
示例7: FindActiveRequest
private bool FindActiveRequest(EasyRequest easy, out IntPtr gcHandlePtr, out ActiveRequest activeRequest)
{
// We maintain an IntPtr=>ActiveRequest mapping, which makes it cheap to look-up by GCHandle ptr but
// expensive to look up by EasyRequest. If we find this becoming a bottleneck, we can add a reverse
// map that stores the other direction as well.
foreach (KeyValuePair<IntPtr, ActiveRequest> pair in _activeOperations)
{
if (pair.Value.Easy == easy)
{
gcHandlePtr = pair.Key;
activeRequest = pair.Value;
return true;
}
}
gcHandlePtr = IntPtr.Zero;
activeRequest = default(ActiveRequest);
return false;
}
示例8: ActivateNewRequest
private void ActivateNewRequest(SafeCurlMultiHandle multiHandle, EasyRequest easy)
{
Debug.Assert(easy != null, "We should never get a null request");
Debug.Assert(easy._associatedMultiAgent == null, "New requests should not be associated with an agent yet");
// If cancellation has been requested, complete the request proactively
if (easy._cancellationToken.IsCancellationRequested)
{
easy.FailRequest(new OperationCanceledException(easy._cancellationToken));
easy.Cleanup(); // no active processing remains, so cleanup
return;
}
// Otherwise, configure it. Most of the configuration was already done when the EasyRequest
// was created, but there's additional configuration we need to do specific to this
// multi agent, specifically telling the easy request about its own GCHandle and setting
// up callbacks for data processing. Once it's configured, add it to the multi handle.
GCHandle gcHandle = GCHandle.Alloc(easy);
IntPtr gcHandlePtr = GCHandle.ToIntPtr(gcHandle);
try
{
easy._associatedMultiAgent = this;
easy.SetCurlOption(CURLoption.CURLOPT_PRIVATE, gcHandlePtr);
SetCurlCallbacks(easy, gcHandlePtr);
ThrowIfCURLMError(Interop.libcurl.curl_multi_add_handle(multiHandle, easy._easyHandle));
}
catch (Exception exc)
{
gcHandle.Free();
easy.FailRequest(exc);
easy.Cleanup(); // no active processing remains, so cleanup
return;
}
// And if cancellation can be requested, hook up a cancellation callback.
// This callback will put the easy request back into the queue, which will
// ensure that a wake-up request has been issued. When we pull
// the easy request out of the request queue, we'll see that it's already
// associated with this agent, meaning that it's a cancellation request,
// and we'll deal with it appropriately.
var cancellationReg = default(CancellationTokenRegistration);
if (easy._cancellationToken.CanBeCanceled)
{
cancellationReg = easy._cancellationToken.Register(s =>
{
var state = (Tuple<MultiAgent, EasyRequest>)s;
state.Item1.Queue(new IncomingRequest { Easy = state.Item2, Type = IncomingRequestType.Cancel });
}, Tuple.Create<MultiAgent, EasyRequest>(this, easy));
}
// Finally, add it to our map.
_activeOperations.Add(
gcHandlePtr,
new ActiveRequest { Easy = easy, CancellationRegistration = cancellationReg });
}
示例9: TransferDataFromRequestStream
/// <summary>
/// Transfers up to <paramref name="length"/> data from the <paramref name="easy"/>'s
/// request content (non-memory) stream to the buffer.
/// </summary>
/// <returns>The number of bytes transferred.</returns>
private static size_t TransferDataFromRequestStream(IntPtr buffer, int length, EasyRequest easy)
{
MultiAgent multi = easy._associatedMultiAgent;
// First check to see whether there's any data available from a previous asynchronous read request.
// If there is, the transfer state's Task field will be non-null, with its Result representing
// the number of bytes read. The Buffer will then contain all of that read data. If the Count
// is 0, then this is the first time we're checking that Task, and so we populate the Count
// from that read result. After that, we can transfer as much data remains between Offset and
// Count. Multiple callbacks may pull from that one read.
EasyRequest.SendTransferState sts = easy._sendTransferState;
if (sts != null)
{
// Is there a previous read that may still have data to be consumed?
if (sts._task != null)
{
Debug.Assert(sts._task.IsCompleted, "The task must have completed if we're getting called back.");
// Determine how many bytes were read on the last asynchronous read.
// If nothing was read, then we're done and can simply return 0 to indicate
// the end of the stream.
int bytesRead = sts._task.GetAwaiter().GetResult(); // will throw if read failed
Debug.Assert(bytesRead >= 0 && bytesRead <= sts._buffer.Length, "ReadAsync returned an invalid result length: " + bytesRead);
if (bytesRead == 0)
{
multi.VerboseTrace("End of stream from stored task", easy: easy);
sts.SetTaskOffsetCount(null, 0, 0);
return 0;
}
// If Count is still 0, then this is the first time after the task completed
// that we're examining the data: transfer the bytesRead to the Count.
if (sts._count == 0)
{
multi.VerboseTrace("ReadAsync completed with bytes: " + bytesRead, easy: easy);
sts._count = bytesRead;
}
// Now Offset and Count are both accurate. Determine how much data we can copy to libcurl...
int availableData = sts._count - sts._offset;
Debug.Assert(availableData > 0, "There must be some data still available.");
// ... and copy as much of that as libcurl will allow.
int bytesToCopy = Math.Min(availableData, length);
Marshal.Copy(sts._buffer, sts._offset, buffer, bytesToCopy);
multi.VerboseTrace("Copied " + bytesToCopy + " bytes from request stream", easy: easy);
// Update the offset. If we've gone through all of the data, reset the state
// so that the next time we're called back we'll do a new read.
sts._offset += bytesToCopy;
Debug.Assert(sts._offset <= sts._count, "Offset should never exceed count");
if (sts._offset == sts._count)
{
sts.SetTaskOffsetCount(null, 0, 0);
}
// Return the amount of data copied
Debug.Assert(bytesToCopy > 0, "We should never return 0 bytes here.");
return (size_t)bytesToCopy;
}
// sts was non-null but sts.Task was null, meaning there was no previous task/data
// from which to satisfy any of this request.
}
else // sts == null
{
// Allocate a transfer state object to use for the remainder of this request.
easy._sendTransferState = sts = new EasyRequest.SendTransferState();
}
Debug.Assert(sts != null, "By this point we should have a transfer object");
Debug.Assert(sts._task == null, "There shouldn't be a task now.");
Debug.Assert(sts._count == 0, "Count should be zero.");
Debug.Assert(sts._offset == 0, "Offset should be zero.");
// If we get here, there was no previously read data available to copy.
// Initiate a new asynchronous read.
Task<int> asyncRead = easy._requestContentStream.ReadAsyncInternal(
sts._buffer, 0, Math.Min(sts._buffer.Length, length), easy._cancellationToken);
Debug.Assert(asyncRead != null, "Badly implemented stream returned a null task from ReadAsync");
// Even though it's "Async", it's possible this read could complete synchronously or extremely quickly.
// Check to see if it did, in which case we can also satisfy the libcurl request synchronously in this callback.
if (asyncRead.IsCompleted)
{
multi.VerboseTrace("ReadAsync completed immediately", easy: easy);
// Get the amount of data read.
int bytesRead = asyncRead.GetAwaiter().GetResult(); // will throw if read failed
if (bytesRead == 0)
{
multi.VerboseTrace("End of stream from quick returning ReadAsync", easy: easy);
return 0;
}
//.........这里部分代码省略.........
示例10: RequestUnpause
/// <summary>Requests that libcurl unpause the connection associated with this request.</summary>
internal void RequestUnpause(EasyRequest easy)
{
VerboseTrace(easy: easy);
Queue(new IncomingRequest { Easy = easy, Type = IncomingRequestType.Unpause });
}
示例11: TryGetEasyRequest
private static bool TryGetEasyRequest(IntPtr curlPtr, out EasyRequest easy)
{
Debug.Assert(curlPtr != IntPtr.Zero, "curlPtr is not null");
IntPtr gcHandlePtr;
CURLcode getInfoResult = Interop.Http.EasyGetInfoPointer(curlPtr, CURLINFO.CURLINFO_PRIVATE, out gcHandlePtr);
Debug.Assert(getInfoResult == CURLcode.CURLE_OK, "Failed to get info on a completing easy handle");
if (getInfoResult == CURLcode.CURLE_OK)
{
try
{
GCHandle handle = GCHandle.FromIntPtr(gcHandlePtr);
easy = (EasyRequest)handle.Target;
Debug.Assert(easy != null, "Expected non-null EasyRequest in GCHandle");
return easy != null;
}
catch (Exception e)
{
EventSourceTrace("Error getting state from GCHandle: {0}", e);
Debug.Fail($"Exception in {nameof(TryGetEasyRequest)}", e.ToString());
}
}
easy = null;
return false;
}
示例12: QueueOperationWithRequestContentAsync
/// <summary>
/// Loads the request's request content stream asynchronously and
/// then submits the request to the multi agent.
/// </summary>
private async Task<HttpResponseMessage> QueueOperationWithRequestContentAsync(EasyRequest easy)
{
Debug.Assert(easy._requestMessage.Content != null, "Expected request to have non-null request content");
easy._requestContentStream = await easy._requestMessage.Content.ReadAsStreamAsync().ConfigureAwait(false);
if (easy._cancellationToken.IsCancellationRequested)
{
easy.FailRequest(new OperationCanceledException(easy._cancellationToken));
easy.Cleanup(); // no active processing remains, so we can cleanup
}
else
{
ConfigureAndQueue(easy);
}
return await easy.Task.ConfigureAwait(false);
}
示例13: ConfigureAndQueue
private void ConfigureAndQueue(EasyRequest easy)
{
try
{
easy.InitializeCurl();
_agent.Queue(new MultiAgent.IncomingRequest { Easy = easy, Type = MultiAgent.IncomingRequestType.New });
}
catch (Exception exc)
{
easy.FailRequest(exc);
easy.Cleanup(); // no active processing remains, so we can cleanup
}
}
示例14: SendAsync
protected internal override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
if (request == null)
{
throw new ArgumentNullException("request", SR.net_http_handler_norequest);
}
if ((request.RequestUri.Scheme != UriSchemeHttp) && (request.RequestUri.Scheme != UriSchemeHttps))
{
throw NotImplemented.ByDesignWithMessage(SR.net_http_client_http_baseaddress_required);
}
if (request.RequestUri.Scheme == UriSchemeHttps && !s_supportsSSL)
{
throw new PlatformNotSupportedException(SR.net_http_unix_https_support_unavailable_libcurl);
}
if (request.Headers.TransferEncodingChunked.GetValueOrDefault() && (request.Content == null))
{
throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content);
}
if (_useCookie && _cookieContainer == null)
{
throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer);
}
// TODO: Check that SendAsync is not being called again for same request object.
// Probably fix is needed in WinHttpHandler as well
CheckDisposed();
SetOperationStarted();
// Do an initial cancellation check to avoid initiating the async operation if
// cancellation has already been requested. After this, we'll rely on CancellationToken.Register
// to notify us of cancellation requests and shut down the operation if possible.
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<HttpResponseMessage>(cancellationToken);
}
// Create the easy request. This associates the easy request with this handler and configures
// it based on the settings configured for the handler.
var easy = new EasyRequest(this, request, cancellationToken);
// Submit the easy request to the multi agent.
if (request.Content != null)
{
// If there is request content to be sent, preload the stream
// and submit the request to the multi agent. This is separated
// out into a separate async method to avoid associated overheads
// in the case where there is no request content stream.
return QueueOperationWithRequestContentAsync(easy);
}
else
{
// Otherwise, just submit the request.
ConfigureAndQueue(easy);
return easy.Task;
}
}
示例15: TryParseStatusLine
private static bool TryParseStatusLine(HttpResponseMessage response, string responseHeader, EasyRequest state)
{
if (!responseHeader.StartsWith(HttpPrefix, StringComparison.OrdinalIgnoreCase))
{
return false;
}
// Clear the header if status line is recieved again. This signifies that there are multiple response headers (like in redirection).
response.Headers.Clear();
response.Content.Headers.Clear();
int responseHeaderLength = responseHeader.Length;
// Check if line begins with HTTP/1.1 or HTTP/1.0
int prefixLength = HttpPrefix.Length;
int versionIndex = prefixLength + 2;
if ((versionIndex < responseHeaderLength) && (responseHeader[prefixLength] == '1') && (responseHeader[prefixLength + 1] == '.'))
{
response.Version =
responseHeader[versionIndex] == '1' ? HttpVersion.Version11 :
responseHeader[versionIndex] == '0' ? HttpVersion.Version10 :
new Version(0, 0);
}
else
{
response.Version = new Version(0, 0);
}
// TODO: Parsing errors are treated as fatal. Find right behaviour
int spaceIndex = responseHeader.IndexOf(SpaceChar);
if (spaceIndex > -1)
{
int codeStartIndex = spaceIndex + 1;
int statusCode = 0;
// Parse first 3 characters after a space as status code
if (TryParseStatusCode(responseHeader, codeStartIndex, out statusCode))
{
response.StatusCode = (HttpStatusCode)statusCode;
// For security reasons, we drop the server credential if it is a
// NetworkCredential. But we allow credentials in a CredentialCache
// since they are specifically tied to URI's.
if ((response.StatusCode == HttpStatusCode.Redirect) && !(state._handler.Credentials is CredentialCache))
{
state.SetCurlOption(CURLoption.CURLOPT_HTTPAUTH, CURLAUTH.None);
state.SetCurlOption(CURLoption.CURLOPT_USERNAME, IntPtr.Zero);
state.SetCurlOption(CURLoption.CURLOPT_PASSWORD, IntPtr.Zero);
state._networkCredential = null;
}
int codeEndIndex = codeStartIndex + StatusCodeLength;
int reasonPhraseIndex = codeEndIndex + 1;
if (reasonPhraseIndex < responseHeaderLength && responseHeader[codeEndIndex] == SpaceChar)
{
int newLineCharIndex = responseHeader.IndexOfAny(s_newLineCharArray, reasonPhraseIndex);
int reasonPhraseEnd = newLineCharIndex >= 0 ? newLineCharIndex : responseHeaderLength;
response.ReasonPhrase = responseHeader.Substring(reasonPhraseIndex, reasonPhraseEnd - reasonPhraseIndex);
}
}
}
return true;
}