本文整理汇总了C#中System.Net.Http.HttpClientHandler类的典型用法代码示例。如果您正苦于以下问题:C# HttpClientHandler类的具体用法?C# HttpClientHandler怎么用?C# HttpClientHandler使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HttpClientHandler类属于System.Net.Http命名空间,在下文中一共展示了HttpClientHandler类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: AuthRequest
private async Task<JObject> AuthRequest(string path, string method, HttpContent data, RequestingUser u) {
using(HttpClientHandler handler = new HttpClientHandler())
using(HttpClient client = new HttpClient(handler)) {
HttpResponseMessage msg = null;
string str;
if(u != null) {
handler.UseCookies = true;
handler.CookieContainer = new CookieContainer();
u.Cookies.ToList().ForEach(c => handler.CookieContainer.Add(c));
client.DefaultRequestHeaders.Add("x-csrf", u.CsrfToken);
}
else {
handler.UseCookies = false;
}
if(method.ToUpper() == WebRequestMethods.Http.Get.ToUpper()) {
msg = await client.GetAsync(BungieNet.PlatformPath + path);
}
else if(method.ToUpper() == WebRequestMethods.Http.Post.ToUpper()) {
msg = await client.PostAsync(BungieNet.PlatformPath + path, data);
}
str = await msg.Content.ReadAsStringAsync();
return JObject.Parse(str);
}
}
开发者ID:d1enamic,项目名称:BungieNetPlatform-CSharp,代码行数:32,代码来源:Platform.cs
示例2: SubmitComment
public static async Task<bool> SubmitComment(string issueNumber, string commentString)
{
// https://developer.atlassian.com/jiradev/api-reference/jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-example-add-comment
// https://grantadesign.atlassian.net/rest/api/latest/project/10000
// https://grantadesign.atlassian.net/rest/api/latest/issue/MI-9111/editmeta/
var credentials = new NetworkCredential(Constants.UserName, Constants.Password);
var handler = new HttpClientHandler {Credentials = credentials, PreAuthenticate = true};
using (var client = new HttpClient(handler))
{
var authHeader = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", Constants.UserName, Constants.Password))));
client.DefaultRequestHeaders.Authorization = authHeader;
client.BaseAddress = new Uri("https://grantadesign.atlassian.net/rest/api/latest/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var jiraComment = new JiraComment { Body = commentString };
var response = await client.PostAsJsonAsync("issue/" + issueNumber + "/comment", jiraComment);
if (response.IsSuccessStatusCode)
{
return true;
}
return false;
}
}
开发者ID:chrispatrick,项目名称:prcreator,代码行数:26,代码来源:JiraWrapper.cs
示例3: CreateHttpClient
private static HttpClient CreateHttpClient(HttpClientHandler handler, string user, string database)
{
return new HttpClient(handler)
{
BaseAddress = new Uri(string.Format("https://{0}.cloudant.com/{1}/", user, database))
};
}
开发者ID:CRHUB,项目名称:haengematte,代码行数:7,代码来源:Program.cs
示例4: OnIdentityProviderTapped
private async void OnIdentityProviderTapped(object sender, TappedRoutedEventArgs e)
{
var identityProvider = (IdentityProvider)((FrameworkElement)e.OriginalSource).DataContext;
var webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
WebAuthenticationOptions.None,
new Uri(identityProvider.LoginUrl),
new Uri("http://authentication.brainthud.com/api/federationcallback/end"));
var start = webAuthenticationResult.ResponseData.LastIndexOf('=') + 1;
var nameIdentifier = webAuthenticationResult.ResponseData.Substring(start, webAuthenticationResult.ResponseData.Length - start);
var cookies = this.getCookies(nameIdentifier);
var uri = new Uri(@"http://www.brainthud.com/api/Cards/");
var cookieContainer = new CookieContainer();
foreach(var cookie in cookies)
{
var cookieItem = new Cookie(cookie.Key, cookie.Value);
cookieContainer.Add(uri, cookieItem);
}
var handler = new HttpClientHandler();
handler.CookieContainer =cookieContainer;
var client = new HttpClient(handler);
var response = client.GetAsync(uri).Result;
var result = response.Content.ReadAsStringAsync().Result;
var x = result;
}
开发者ID:aenmeyk,项目名称:BrainThud,代码行数:29,代码来源:LoginView.xaml.cs
示例5: GetCardsForSet
public IEnumerable<dynamic> GetCardsForSet(string setName)
{
// Undocumented feature to fix "The input stream contains too many delimiter characters" exception.
// See http://forums.asp.net/post/4845421.aspx
// Shouldn't be needed anymore once JSON.NET support is added to HttpClient post-beta.
System.Net.Http.Formatting.MediaTypeFormatter.SkipStreamLimitChecks = true;
var clientHandler = new HttpClientHandler
{
Credentials = new System.Net.NetworkCredential(ServiceUsername, ServicePassword)
};
using(var client = new HttpClient(clientHandler))
{
client.BaseAddress = new Uri(ServiceUrl);
string setUrlPath = String.Format("sets/{0}", Uri.EscapeUriString(setName));
var response = client.GetAsync(setUrlPath).Result;
response.EnsureSuccessStatusCode();
var set = response.Content.ReadAsAsync<System.Json.JsonObject>().Result;
var cards = set["cards"].ReadAs<JsonArray>();
return cards;
}
}
开发者ID:Jaecen,项目名称:HelloCSharpWeb,代码行数:26,代码来源:HunterService.cs
示例6: Main
static void Main(string[] args)
{
//read config data from a command line parameters
var user = args[0];
var password = args[1];
var database = args[2];
//base request builder for all requests containing user name and database name
var handler = new HttpClientHandler { Credentials = new NetworkCredential(user, password) };
using (var client = CreateHttpClient(handler, user, database))
{
var creationResponse = Create(client, new {name = "john", age = 15});
PrintResponse(creationResponse);
var id = GetString("id", creationResponse);
var readResponse = Read(client, id);
PrintResponse(readResponse);
var rev1 = GetString("_rev", readResponse);
var updateResponse = Update(client, id, new {name = "john", age = 36, _rev = rev1});
PrintResponse(updateResponse);
var rev2 = GetString("rev", updateResponse); // note that an update produces a "rev" in the response rather than "_rev"
var deleteResponse = Delete(client, id, rev2);
PrintResponse(deleteResponse);
}
}
开发者ID:CRHUB,项目名称:haengematte,代码行数:28,代码来源:Program.cs
示例7: ExecuteAsync
/// <summary>
/// Executes the provided request asynchronously, returning the response object.
/// </summary>
/// <param name="request"><see cref="ISteamRequest"/> object for execution.</param>
/// <returns><see cref="ISteamResponse"/> object containing the result of the request.</returns>
public async Task<ISteamResponse> ExecuteAsync( ISteamRequest request ) {
AuthenticateClient( this, request );
HttpRequestMessage httpRequest = BuildHttpRequest( request );
CookieContainer cookieContainer = new CookieContainer();
if( request.Cookies == null || request.Cookies.Count > 0 ) {
foreach( Cookie cookie in request.Cookies )
cookieContainer.Add( httpRequest.RequestUri, cookie );
}
HttpClientHandler httpHandler = new HttpClientHandler();
httpHandler.CookieContainer = cookieContainer;
using( var httpClient = new HttpClient( httpHandler ) ){
httpClient.Timeout = TimeSpan.FromMilliseconds( ( ( request.Timeout > 0 ) ? request.Timeout : this.Timeout ) );
try {
request.IncreaseNumAttempts();
return ConvertToResponse( request, await httpClient.SendAsync( httpRequest ), cookieContainer );
}catch( Exception ex ) {
if( ex.InnerException != null && ex.InnerException is WebException )
return CreateErrorResponse( request, ex.InnerException );
return CreateErrorResponse( request, ex );
}
}
}
开发者ID:chaoscode,项目名称:SteamSharp,代码行数:37,代码来源:SteamClient.Async.cs
示例8: Authenticate
/// <summary>
/// Authenticates a user.
/// </summary>
/// <param name="userName">Name of the user.</param>
/// <param name="password">The password.</param>
/// <param name="regionKey">The region key.</param>
/// <returns>The async <see cref="Task"/>.</returns>
public static async Task<CaasAccountDetails> Authenticate(string userName, string password, string regionKey)
{
var config = (ComputeConfigurationSection)ConfigurationManager.GetSection("compute");
var credentials = new NetworkCredential(userName, password);
var handler = new HttpClientHandler { Credentials = credentials };
using (var client = new HttpClient(handler))
{
var region = config.Regions.Cast<RegionConfigurationElement>().FirstOrDefault(r => r.Key == regionKey);
if (region == null)
{
throw new ArgumentException($"The region with key '{regionKey}' does not exist in the app.config file.");
}
var responseSteam = await client.GetStreamAsync(region.BaseUrl + AuthUrl);
var xdoc = XDocument.Load(responseSteam);
XNamespace ns5 = "http://oec.api.opsource.net/schemas/directory";
var orgId = xdoc.Root.Element(ns5 + "orgId").Value;
return new CaasAccountDetails
{
Credentials = new NetworkCredential(userName, password),
OrgId = orgId,
BaseUrl = region.BaseUrl,
Roles = xdoc.Root.Elements(ns5 + "roles").Elements(ns5 + "role").Elements(ns5 + "name").Select(e => e.Value).ToList()
};
}
}
开发者ID:DimensionDataCBUSydney,项目名称:CaaSDeploy,代码行数:34,代码来源:CaaSAuthentication.cs
示例9: Main
static void Main(string[] args)
{
var user = "55bd2041-ef4a-4dec-8bc1-b4aa8871b38f-bluemix";
var password = "cbcdf64595e4ed9d5546e7f9761a03153c3246d97458734c58cfef0f7b06da63";
var database = "database";
var handler = new HttpClientHandler { Credentials = new NetworkCredential(user, password) };
using (var client = CreateHttpClient(handler, user, database))
{
string GetAllResponse = GetAll(client);//Query for all docs
Console.Write(GetAllResponse);
var creationResponse = Create(client, new {item = "carrot", check = false});
PrintResponse(creationResponse);
var id = GetString("id", creationResponse);//Read a doc
var readResponse = Read(client, id);
PrintResponse(readResponse);
var rev1 = GetString("_rev", readResponse);//Update
var updateResponse = Update(client, id, new {item = "carrot", check = true, _rev = rev1});
PrintResponse(updateResponse);
var rev2 = GetString("rev", updateResponse); //Delete
var deleteResponse = Delete(client, id, rev2);
PrintResponse(deleteResponse);
Console.Read();
}
}
开发者ID:achalshant,项目名称:Cloudant-Test-C-Sharp,代码行数:29,代码来源:Program.cs
示例10: DigestCredentials
public void DigestCredentials()
{
var requestUri = new Uri("http://localhost/DigestAuthDemo/");
var credCache = new CredentialCache
{
{
new Uri("http://localhost/"),
"Digest",
new NetworkCredential("Test", "Test", "/")
}
};
using (var clientHander = new HttpClientHandler
{
Credentials = credCache,
PreAuthenticate = true
})
using (var httpClient = new HttpClient(clientHander))
{
for (var i = 0; i < 5; i++)
{
var responseTask = httpClient.GetAsync(requestUri);
responseTask.Result.EnsureSuccessStatusCode();
}
}
}
开发者ID:fsimonazzi,项目名称:DigestAuthDemo,代码行数:27,代码来源:DigestAuthTests.cs
示例11: NodeEngine
public NodeEngine()
{
_port = 1337;
var sb = new StringBuilder(File.ReadAllText("server.js"));
// add included scripts
sb.AppendLine("var Handlebars = require('./Script/handlebars-1.0.0.js');");
foreach (var script in HandlebarsConfiguration.Instance.Include)
{
if (!string.IsNullOrEmpty(script.Name))
{
sb.AppendLine("var " + script.Name + " = require('./" + script.Source + "');");
}
else
{
sb.AppendLine("require('./" + script.Source + "');");
}
}
File.WriteAllText("hb-server.js", sb.ToString());
_server = new Process();
_server.StartInfo = GetStartInfo();
_server.Start();
HttpClientHandler handler = new HttpClientHandler();
handler.AllowAutoRedirect = true;
handler.AutomaticDecompression = DecompressionMethods.None;
_client = new HttpClient(handler);
}
开发者ID:jamisliao,项目名称:handlebars-net,代码行数:30,代码来源:NodeEngine.cs
示例12: Post
public static string Post(string url, PostBody postBody, int timeout = 5000)
{
try
{
Logger.Debug($"Post\t{url}");
using (var handler = new HttpClientHandler() { CookieContainer = new CookieContainer() })
using (var client = new HttpClient(handler))
{
var content = new FormUrlEncodedContent(postBody.Body);
var magicCodeName = string.Empty;
if (Config.TryGet("MagicCodeType", out magicCodeName))
{
var magicCodeValue = Config.TryGet("MagicCodeValue", "");
var magicCodePath = Config.TryGet("MagicCodePath", "/");
var magicCodeDomain = Config.TryGet("MagicCodeDomain", ".baidu.com");
handler.CookieContainer.Add(new Cookie(magicCodeName, magicCodeValue, magicCodePath, magicCodeDomain));
}
var result = client.PostAsync(url, content).Result;
result.EnsureSuccessStatusCode();
return result.Content.ReadAsStringAsync().Result;
}
}
catch (Exception e)
{
Logger.Error(e.ToString());
return e.Message;
}
}
开发者ID:chinaboard,项目名称:WeeklyRobot,代码行数:30,代码来源:HttpHelper.cs
示例13: Execute
/// <summary>
/// You need to put this activity in a different agent that write the diagnostics log that you want to change.
/// </summary>
/// <param name="context"></param>
protected override void Execute(CodeActivityContext context)
{
Thread.Sleep(30000);
var findAndReplace = context.GetValue(FindAndReplaceStrings);
_teamProjectUri = context.GetValue(TeamProjectUri);
_buildUri = context.GetValue(BuildUri);
var vssCredential = new VssCredentials(true);
_fcClient = new FileContainerHttpClient(_teamProjectUri, vssCredential);
var containers = _fcClient.QueryContainersAsync(new List<Uri>() { _buildUri }).Result;
if (!containers.Any())
return;
var agentLogs = GetAgentLogs(containers);
if (agentLogs == null)
return;
using (var handler = new HttpClientHandler() { UseDefaultCredentials = true })
{
var reader = DownloadAgentLog(agentLogs, handler);
using (var ms = new MemoryStream())
{
ReplaceStrings(findAndReplace, reader, ms);
var response = UploadDocument(containers, agentLogs, ms);
}
}
}
开发者ID:GersonDias,项目名称:OpenSource,代码行数:35,代码来源:ReplaceDiagnosticsInfo.cs
示例14: LogOnAsync
// <snippet508>
public async Task<LogOnResult> LogOnAsync(string userId, string password)
{
using (var handler = new HttpClientHandler { CookieContainer = new CookieContainer() })
{
using (var client = new HttpClient(handler))
{
client.AddCurrentCultureHeader();
// Ask the server for a password challenge string
var requestId = GenerateRequestId();
var response1 = await client.GetAsync(_clientBaseUrl + "GetPasswordChallenge?requestId=" + requestId);
response1.EnsureSuccessStatusCode();
var challengeEncoded = await response1.Content.ReadAsAsync<string>();
var challengeBuffer = CryptographicBuffer.DecodeFromHexString(challengeEncoded);
// Use HMAC_SHA512 hash to encode the challenge string using the password being authenticated as the key.
var provider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha512);
var passwordBuffer = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8);
var hmacKey = provider.CreateKey(passwordBuffer);
var buffHmac = CryptographicEngine.Sign(hmacKey, challengeBuffer);
var hmacString = CryptographicBuffer.EncodeToHexString(buffHmac);
// Send the encoded challenge to the server for authentication (to avoid sending the password itself)
var response = await client.GetAsync(_clientBaseUrl + userId + "?requestID=" + requestId +"&passwordHash=" + hmacString);
// Raise exception if sign in failed
response.EnsureSuccessStatusCode();
// On success, return sign in results from the server response packet
var result = await response.Content.ReadAsAsync<UserInfo>();
var serverUri = new Uri(Constants.ServerAddress);
return new LogOnResult { ServerCookieHeader = handler.CookieContainer.GetCookieHeader(serverUri), UserInfo = result };
}
}
}
开发者ID:stevenh77,项目名称:ItineraryHunter-Win8,代码行数:35,代码来源:IdentityServiceProxy.cs
示例15: SendSMS
public void SendSMS(Models.Message message)
{
var from = Settings.FromPhoneNumber;
var phonePrefix = Settings.PhonePrefix;
var handler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip,
AllowAutoRedirect = false,
UseCookies = true
};
var httpclient = new HttpClient(handler);
httpclient.BaseAddress = new Uri("https://www.ovh.com");
var request = "cgi-bin/sms/http2sms.cgi"
.SetQueryParam("account", Settings.Account)
.SetQueryParam("login", Settings.Nic)
.SetQueryParam("password", Settings.Password)
.SetQueryParam("from", from)
.SetQueryParam("to", message.MobileNumber)
.SetQueryParam("message", message.Content)
.SetQueryParam("noStop", "1");
var response = httpclient.GetAsync(request);
if (response.Result.StatusCode == HttpStatusCode.OK)
{
var content = response.Result.Content.ReadAsStringAsync().Result;
}
}
开发者ID:chouteau,项目名称:sitesurveyor,代码行数:29,代码来源:SmsService.cs
示例16: ChkVerifyCodeAnsyn
public static async Task<bool> ChkVerifyCodeAnsyn(string verifyNo)
{
try
{
var handler = new HttpClientHandler() { CookieContainer = cookieContainers, AllowAutoRedirect = true, AutomaticDecompression = DecompressionMethods.GZip };
using (var httpClient = new HttpClient(handler))
{
httpClient.DefaultRequestHeaders.Add("Host", "kyfw.12306.cn");
httpClient.DefaultRequestHeaders.Add("Origin", ConstantKey.loginorigin);
httpClient.DefaultRequestHeaders.Add("Referer", ConstantKey.loginRefer);
httpClient.DefaultRequestHeaders.Add("UserAgent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131");
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) => true;
// 构造POST参数
var data = new FormUrlEncodedContent(new Dictionary<string, string>()
{
{"randCode", verifyNo},
{"rand", "sjrand"}
});
var response = await httpClient.PostAsync(ConstantKey.loginChkVcode, data);
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
if (string.IsNullOrEmpty(content) || !content.Contains("Y") || !content.Contains("true")) return false;
return true;
}
}
catch (Exception ex)
{
return false;
}
}
开发者ID:zhouyongtao,项目名称:TicketHelper,代码行数:30,代码来源:TicketHandler.cs
示例17: LoginInitAndGetloginVcode
public static async Task<Image> LoginInitAndGetloginVcode(bool IsFirst = false)
{
try
{
var handler = new HttpClientHandler() { CookieContainer = cookieContainers, AllowAutoRedirect = true, AutomaticDecompression = DecompressionMethods.GZip };
using (var httpClient = new HttpClient(handler))
{
httpClient.DefaultRequestHeaders.Add("Host", "kyfw.12306.cn");
httpClient.DefaultRequestHeaders.Add("Origin", ConstantKey.loginorigin);
httpClient.DefaultRequestHeaders.Add("Referer", ConstantKey.loginRefer);
httpClient.DefaultRequestHeaders.Add("UserAgent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131");
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) => true;
if (IsFirst)
{
//loginInit
string loginInit = await httpClient.GetStringAsync(ConstantKey.loginInit);
if (string.IsNullOrEmpty(loginInit) || !loginInit.Contains("登录")) return null;
//loginJs
var resp = await httpClient.GetAsync(ConstantKey.loginJs);
if (!resp.IsSuccessStatusCode) return null;
}
//VerifyCode
var verifyStream = await httpClient.GetStreamAsync(ConstantKey.loginVcode);
if (verifyStream == null) return null;
return Image.FromStream(verifyStream);
}
}
catch (Exception ex)
{
return null;
}
}
开发者ID:zhouyongtao,项目名称:TicketHelper,代码行数:32,代码来源:TicketHandler.cs
示例18: Initalize
private void Initalize()
{
// Limit to maximum of 256 Connections
ServicePointManager.DefaultConnectionLimit = 256;
//Trust all certificates
ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);
// TODO: Add Proxy Support
Handler = new HttpClientHandler
{
AllowAutoRedirect = true,
UseCookies = true,
CookieContainer = new CookieContainer(),
UseDefaultCredentials = false,
Proxy = null,
UseProxy = false
};
// Create the HTTP Client
Client = new HttpClient(Handler);
Client.DefaultRequestHeaders.Clear();
Client.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue { MaxAge = TimeSpan.FromSeconds(0) };
Client.DefaultRequestHeaders.Accept.ParseAdd("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
Client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36");
}
开发者ID:joshimoo,项目名称:TwitchBot,代码行数:26,代码来源:TwitchClient.cs
示例19: CreateHttpClientHandler
public static HttpClientHandler CreateHttpClientHandler()
{
var handler = new HttpClientHandler();
handler.ApplyProxy();
return handler;
}
开发者ID:Kyrodan,项目名称:KeeAnywhere,代码行数:7,代码来源:ProxyTools.cs
示例20: CreateClientHandler
public static HttpClientHandler CreateClientHandler(string serviceUrl, ICredentials credentials)
{
if (serviceUrl == null)
{
throw new ArgumentNullException("serviceUrl");
}
// Set up our own HttpClientHandler and configure it
HttpClientHandler clientHandler = new HttpClientHandler();
if (credentials != null)
{
// Set up credentials cache which will handle basic authentication
CredentialCache credentialCache = new CredentialCache();
// Get base address without terminating slash
string credentialAddress = new Uri(serviceUrl).GetLeftPart(UriPartial.Authority).TrimEnd(uriPathSeparator);
// Add credentials to cache and associate with handler
NetworkCredential networkCredentials = credentials.GetCredential(new Uri(credentialAddress), "Basic");
credentialCache.Add(new Uri(credentialAddress), "Basic", networkCredentials);
clientHandler.Credentials = credentialCache;
clientHandler.PreAuthenticate = true;
}
// Our handler is ready
return clientHandler;
}
开发者ID:johnkors,项目名称:azure-sdk-tools,代码行数:28,代码来源:HttpClientHelper.cs
注:本文中的System.Net.Http.HttpClientHandler类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论