本文整理汇总了C#中System.Net.Http.WebRequestHandler类的典型用法代码示例。如果您正苦于以下问题:C# WebRequestHandler类的具体用法?C# WebRequestHandler怎么用?C# WebRequestHandler使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
WebRequestHandler类属于System.Net.Http命名空间,在下文中一共展示了WebRequestHandler类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Persist
public void Persist(TrackerData trackerData)
{
// setup the client
// - with a custome handler to approve all server certificates
var handler = new WebRequestHandler
{
ServerCertificateValidationCallback =
(sender, certificate, chain, errors) => true
};
try
{
using (var client = new HttpClient(handler))
{
// post it
HttpResponseMessage httpResponseMessage = client.PostAsJsonAsync(_serviceUrl, trackerData).Result;
if (!httpResponseMessage.IsSuccessStatusCode)
{
Configurator.Configuration.Logger.Warn(string.Format("Data not persisted with status {0}",
httpResponseMessage.StatusCode));
}
}
}
catch (Exception ex)
{
Configurator.Configuration.Logger.Error(ex.Message, ex);
}
}
示例2: execute
static async Task execute(
string authority,
string resourceUri,
string thisAppClientID,
string thisAppKey,
string epAddress
)
{
using (var handler = new WebRequestHandler())
{
handler.ServerCertificateValidationCallback += (sender, x509cert, chain, policyerrs) => { return true; };
using (var client = new HttpClient(handler))
{
var authToken = await getAuthToken(authority,
resourceUri,
thisAppClientID,
thisAppKey);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + authToken);
// client.DefaultRequestHeaders.Add("Authorization", "Bearer " + "BS HERE");
var response = await client.GetAsync(new Uri(epAddress));
Console.WriteLine("ep: {0} - Response: {1}", epAddress, response.StatusCode);
}
}
}
示例3: ProcessAttachment
public async Task ProcessAttachment(long incidentId, string fileName)
{
String fileAsBase64 = Convert.ToBase64String(File.ReadAllBytes(fileName));
AttachmentWrapper payload = new AttachmentWrapper();
payload.Attachment = IncidentAttachment.CreateIncidentAttachment(Path.GetFileName(fileName), fileAsBase64);
string createAttachementUri = "https://icm.ad.msft.net/api/cert/incidents(" + incidentId
+ ")/CreateAttachment";
Logger.DebugFormat("CreateAttachementUri {0}", createAttachementUri);
try
{
using (WebRequestHandler handler = new WebRequestHandler())
{
handler.ClientCertificates.Add(certificate);
using (HttpClient client = new HttpClient(handler))
{
client.BaseAddress = new Uri(createAttachementUri);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.PostAsJsonAsync(createAttachementUri, payload);
Logger.InfoFormat(response.ToString());
}
}
}
catch (Exception ex)
{
Logger.ErrorFormat(ex.ToString());
}
}
示例4: HttpClientJsonRequestTest
public async Task HttpClientJsonRequestTest()
{
var handler = new WebRequestHandler();
//handler.Proxy = new WebProxy("http://localhost:8888/");
//handler.Credentials = new NetworkCredential(uid, pwd);
var client = new HttpClient(handler);
var postSnippet = new CodeSnippet()
{
UserId = "Bogus",
Code = "string.Format('Hello World, I will own you!');",
Comment = "World domination imminent"
};
// this isn't actually an API so the POST is ignored
// but it always returns a JSON response
string url = "http://codepaste.net/recent?format=json";
var response = await client.PostAsync(url, postSnippet,
new JsonMediaTypeFormatter(), null);
Assert.IsTrue(response.IsSuccessStatusCode);
var snippets = await response.Content.ReadAsAsync<List<CodeSnippet>>();
Assert.IsTrue(snippets.Count > 0);
foreach (var snippet in snippets)
{
if (string.IsNullOrEmpty(snippet.Code))
continue;
Console.WriteLine(snippet.Code.Substring(0, Math.Min(snippet.Code.Length, 200)));
Console.WriteLine("--");
}
}
示例5: Check
public BuildStatusCollection Check()
{
var status = new BuildStatusCollection();
string response = "NO RESPONSE";
try
{
var webRequestHandler = new WebRequestHandler();
if (!string.IsNullOrWhiteSpace(Settings.Default.TeamCityUser) && !string.IsNullOrWhiteSpace(Settings.Default.TeamCityPassword))
{
webRequestHandler.Credentials = new NetworkCredential(Settings.Default.TeamCityUser, Settings.Default.TeamCityPassword);
}
using (var client = new HttpClient(webRequestHandler))
{
client.BaseAddress = new Uri(Settings.Default.TeamCityUrl);
logger.Debug("Getting status from TeamCity at URL [{0}] with user [{1}] and password [{2}]", new Uri(client.BaseAddress, REQUEST_PATH), Settings.Default.TeamCityUser ?? "Anonymous",
Settings.Default.TeamCityPassword ?? "N/A");
response = client.GetStringAsync(REQUEST_PATH).Result;
logger.Debug("Response from server is {0}", response);
return new BuildStatusCollection(response);
}
}
catch (Exception err)
{
logger.ErrorException(
string.Format(
"Unexpected exception occured when checking status at TeamCity. URL [{0}], User [{1}], Password [{2}], RawResponse [{3}]",
Settings.Default.TeamCityUrl ?? " NULL", Settings.Default.TeamCityUser ?? "Anonymous",
Settings.Default.TeamCityPassword ?? "N/A", response), err);
}
return status;
}
示例6: CreateWebClient
public HttpClient CreateWebClient()
{
if(handler == null)
{
if (ClientCertificate == null)
throw new NullReferenceException("ClientCertificate is null.");
if (ServerCertificateValidator == null)
throw new NullReferenceException("ServerCertificateValidator is null.");
if (BaseUrl == null)
throw new NullReferenceException("BaseUrl is null.");
handler = new WebRequestHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ClientCertificates.Add(ClientCertificate);
handler.ServerCertificateValidationCallback = ServerCertificateValidator;
}
if (client == null)
{
client = new HttpClient(handler);
client.DefaultRequestHeaders.Add("x-devupdater-client-version", version.ToString()); // send version (next version will be able to reject older versions)
}
return client;
}
示例7: Main
static void Main(string[] args)
{
var handler = new WebRequestHandler();
handler.ClientCertificates.Add(
X509.CurrentUser
.My
.SubjectDistinguishedName
.Find("CN=client")
.First());
//var handler = new HttpClientHandler
//{
// ClientCertificateOptions = ClientCertificateOption.Automatic
//};
var client = new HttpClient(handler)
{
BaseAddress = new Uri("https://web.local:444/api/")
};
client.SetBasicAuthentication("bob", "bob");
var result = client.GetStringAsync("identity").Result;
Console.WriteLine(JArray.Parse(result));
}
示例8: SystemNetHttpClientAdapter
public SystemNetHttpClientAdapter(AdapterOptions options)
{
_autoRedirect = options.AutoRedirect;
var handler = new WebRequestHandler
{
AllowAutoRedirect = !(AutoRedirect.AutoRedirectAndForwardAuthorizationHeader.Equals(options.AutoRedirect) ||
AutoRedirect.DoNotAutoRedirect.Equals(options.AutoRedirect)),
UseCookies = false,
};
if (options.CachePolicy.Cache)
{
handler.CachePolicy = new RequestCachePolicy(RequestCacheLevel.Default);
}
if (options.AcceptEncoding.AcceptGzipAndDeflate)
{
handler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
}
_client = new HttpClient(handler);
if (options.Timeout != null)
{
_client.Timeout = options.Timeout.TimeSpan;
}
}
示例9: Main
//static Uri _baseAddress = new Uri(Constants.SelfHostBaseAddress);
static void Main(string[] args)
{
while (true)
{
Helper.Timer(() =>
{
"Calling Service\n".ConsoleYellow();
var handler = new WebRequestHandler();
handler.ClientCertificates.Add(
X509.
CurrentUser.
My.
SubjectDistinguishedName.
Find("CN=Client").First());
var client = new HttpClient(handler) { BaseAddress = _baseAddress };
var response = client.GetAsync("identity").Result;
response.EnsureSuccessStatusCode();
var identity = response.Content.ReadAsAsync<Identity>().Result;
identity.ShowConsole();
});
Console.ReadLine();
}
}
示例10: RunAsync
protected override async Task RunAsync(HttpApiContext context)
{
using (WebRequestHandler handler = new WebRequestHandler())
{
handler.UseCookies = false;
handler.AllowAutoRedirect = false;
handler.ServerCertificateValidationCallback = delegate { return true; };
//handler.ClientCertificateOptions = ClientCertificateOption.Automatic;
handler.AutomaticDecompression = System.Net.DecompressionMethods.Deflate | System.Net.DecompressionMethods.GZip;
using (HttpClient client = new HttpClient(handler))
{
HttpRequestMessage request = Create(context.Request);
var response = await client.SendAsync(request);
var data = await response.Content.ReadAsByteArrayAsync();
context.Response = SetResponse(response, data);
var ct = response.Content.Headers.ContentType;
if (ct != null)
{
context.Response.ContentType = ct.ToString();
}
//context.Response.ContentType = response.Content.Headers.ContentType.ToString();
}
}
}
示例11: getWebRequestHandlerWithCert
private WebRequestHandler getWebRequestHandlerWithCert(string certFilename)
{
var cert = new X509Certificate2(certFilename, "");
var clientHandler = new WebRequestHandler();
clientHandler.ClientCertificates.Add(cert);
return clientHandler;
}
示例12: HttpClientAbstraction
internal HttpClientAbstraction(HttpClient client, IAbstractionContext context, WebRequestHandler handler, bool ignoreSslErrors)
: this(client, handler, ignoreSslErrors)
{
if (context.Logger.IsNotNull())
{
this.instanceLogger = context.Logger;
}
this.cancellationToken = context.CancellationToken;
}
示例13: initHttpClientInstance
private HttpClient initHttpClientInstance(WebRequestHandler clientHandler, string appKey, string baseUrl = DEFAULT_COM_BASEURL)
{
var client = new HttpClient(clientHandler);
client.BaseAddress = new Uri(baseUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("X-Application", appKey);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return client;
}
示例14: CreateHttpClient
// We use the same HttpClient for all calls to the same subscription; this allows DNS and proxy details to be
// cached across requests. Note that HttpClient allows parallel operations.
internal static HttpClient CreateHttpClient (Subscription subscription, string msVersion, Func<IEnumerable<TraceListener>> listenerFunc)
{
var handler = new WebRequestHandler();
handler.ClientCertificates.Add(subscription.ManagementCertificate);
var logger = new LoggingHandler(handler, listenerFunc);
var client = new HttpClient(logger, true);
client.DefaultRequestHeaders.Add("x-ms-version", msVersion);
return client;
}
示例15: CreateVMManagementClient
/// <summary>
/// Allan Alderman 1-10-2014
/// Assembles a VM Managment client, attaching the correct management certificate.
/// </summary>
/// <returns>An HTTP client that is ready and authorized to issue commands to Azure's REST API.</returns>
public static HttpClient CreateVMManagementClient()
{
if (_http != null) return _http;
var handler = new WebRequestHandler();
handler.ClientCertificates.Add(ConstructX509Certificate());
_http = new HttpClient(handler) {BaseAddress = new Uri(AzureVmRestApiUri)};
_http.DefaultRequestHeaders.Add("x-ms-version", "2013-08-01");
return _http;
}