本文整理汇总了C#中System.Net.Http.HttpClient类的典型用法代码示例。如果您正苦于以下问题:C# HttpClient类的具体用法?C# HttpClient怎么用?C# HttpClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HttpClient类属于System.Net.Http命名空间,在下文中一共展示了HttpClient类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: Button_Click
private async void Button_Click(object sender, RoutedEventArgs e)
{
if (CountryPhoneCode.SelectedItem != null)
{
var _id = Guid.NewGuid().ToString("N");
var _countryPhoneCode = (CountryPhoneCode.SelectedItem as Country).PhoneCode;
var _countryName = (CountryPhoneCode.SelectedItem as Country).CountryName;
var _name = FullName.Text;
var _phoneNumber = PhoneNumber.Text;
var _password = Password.Password;
var client = new HttpClient()
{
BaseAddress = new Uri("http://yochat.azurewebsites.net/chat/")
};
var json = await client.GetStringAsync("createuser?id=" + _id + "&fullName=" + _name + "&password=" + _password + "&phoneNumber=" + _phoneNumber + "&countryPhoneCode=" + _countryPhoneCode);
var serializer = new DataContractJsonSerializer(typeof(User));
var ms = new MemoryStream();
var user = serializer.ReadObject(ms) as User;
Frame.Navigate(typeof(MainPage), user);
}
else
{
MessageDialog dialog = new MessageDialog("Lütfen Ülkenizi Seçiniz!");
await dialog.ShowAsync();
}
}
开发者ID:yavuzgedik,项目名称:Windows10_UWP,代码行数:30,代码来源:LoginPage.xaml.cs
示例2: Create_New_Customer
public void Create_New_Customer()
{
Uri baseAddress = new Uri("http://localhost:8080/");
CustomServiceHost host = new CustomServiceHost(typeof(CustomerService), baseAddress);
using (host)
{
host.Open();
HttpClient client = new HttpClient(baseAddress);
client.Channel = new WebRequestChannel();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "Customers");
request.Content = new StringContent("Id = 7; Name = NewCustomer7");
HttpResponseMessage response = client.Send(request);
using (response)
{
Assert.IsNotNull(response, "The response should not have been null.");
Assert.AreEqual(HttpStatusCode.Created, response.StatusCode, "The status code should have been 'Created'.");
Assert.IsNotNull(response.Headers.Location, "The location header should not have been null.");
Assert.AreEqual(new Uri("http://localhost:8080/Customers?id=7"), response.Headers.Location, "The location header should have beeen 'http://localhost:8080/Customers?id=7'.");
Assert.AreEqual("Id = 7; Name = NewCustomer7", response.Content.ReadAsString(), "The response content should have been 'Id = 7; Name = NewCustomer7'.");
}
// Put server back in original state
request = new HttpRequestMessage(HttpMethod.Delete, "Customers?id=7");
client.Send(request);
}
}
开发者ID:nuxleus,项目名称:WCFWeb,代码行数:27,代码来源:ScenarioTests.cs
示例3: Mvc200RequestFW45BasicRequestSyntheticFiltering
public void Mvc200RequestFW45BasicRequestSyntheticFiltering()
{
const string requestPath = "api/products";
const string expectedRequestName = "GET products";
string expectedRequestUrl = this.Config.ApplicationUri + "/" + requestPath;
DateTimeOffset testStart = DateTimeOffset.UtcNow;
//Call an applicaiton page
var client = new HttpClient();
var requestMessage = new HttpRequestMessage
{
RequestUri = new Uri(expectedRequestUrl),
Method = HttpMethod.Get,
};
requestMessage.Headers.Add("User-Agent", "bingbot");
var responseTask = client.SendAsync(requestMessage);
responseTask.Wait(TimeoutInMs);
var responseTextTask = responseTask.Result.Content.ReadAsStringAsync();
responseTextTask.Wait(TimeoutInMs);
Assert.IsTrue(responseTextTask.Result.StartsWith("[{"));
var request = Listener.ReceiveItemsOfType<TelemetryItem<RequestData>>(1, TimeoutInMs)[0];
var testFinish = DateTimeOffset.UtcNow;
this.TestWebApplicationHelper(expectedRequestName, expectedRequestUrl, "200", true, request, testStart, testFinish);
Assert.AreEqual("Spider", request.OperationContext.SyntheticSource);
}
开发者ID:jawn,项目名称:ApplicationInsights-server-dotnet,代码行数:31,代码来源:WebAppFW45Tests.cs
示例4: About
public ActionResult About(string searchString)
{
if(searchString=="" || searchString==null)
{
searchString = "Jurasic Park";
}
List<Movie> mo = new List<Movie>();
string responseString = "";
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:51704/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync("api/movie?name=" + searchString).Result;
if (response.IsSuccessStatusCode)
{
responseString = response.Content.ReadAsStringAsync().Result;
}
}
string jsonInput=responseString; //
System.Console.Error.WriteLine(responseString);
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
mo= jsonSerializer.Deserialize<List<Movie>>(jsonInput);
return View(mo);
}
开发者ID:nantharupan,项目名称:MVC_MovieSearch,代码行数:30,代码来源:HomeController.cs
示例5: ButtonAccessResource_Click
private async void ButtonAccessResource_Click(object sender, RoutedEventArgs e)
{
var client = new HttpClient {
BaseAddress = _baseAddress
};
if (_credential != null)
{
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", _credential.AccessToken);
}
var response = await client.GetAsync("identity");
if (response.StatusCode != System.Net.HttpStatusCode.OK)
{
var md = new MessageDialog(response.ReasonPhrase);
await md.ShowAsync();
return;
}
var claims = await response.Content.ReadAsAsync<IEnumerable<ViewClaim>>();
foreach (var claim in claims)
{
ListClaims.Items.Add(string.Format("{0}: {1}", claim.Type, claim.Value));
}
}
开发者ID:nanderto,项目名称:Thinktecture.AuthorizationServer,代码行数:27,代码来源:MainPage.xaml.cs
示例6: SetupAutoCADIOContainer
/// <summary>
/// Does setup of AutoCAD IO.
/// This method will need to be invoked once before any other methods of this
/// utility class can be invoked.
/// </summary>
/// <param name="autocadioclientid">AutoCAD IO Client ID - can be obtained from developer.autodesk.com</param>
/// <param name="autocadioclientsecret">AutoCAD IO Client Secret - can be obtained from developer.autodesk.com</param>
public static void SetupAutoCADIOContainer(String autocadioclientid, String autocadioclientsecret)
{
try
{
String clientId = autocadioclientid;
String clientSecret = autocadioclientsecret;
Uri uri = new Uri("https://developer.api.autodesk.com/autocad.io/us-east/v2/");
container = new AIO.Operations.Container(uri);
container.Format.UseJson();
using (var client = new HttpClient())
{
var values = new List<KeyValuePair<string, string>>();
values.Add(new KeyValuePair<string, string>("client_id", clientId));
values.Add(new KeyValuePair<string, string>("client_secret", clientSecret));
values.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
var requestContent = new FormUrlEncodedContent(values);
var response = client.PostAsync("https://developer.api.autodesk.com/authentication/v1/authenticate", requestContent).Result;
var responseContent = response.Content.ReadAsStringAsync().Result;
var resValues = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseContent);
_accessToken = resValues["token_type"] + " " + resValues["access_token"];
if (!string.IsNullOrEmpty(_accessToken))
{
container.SendingRequest2 += (sender, e) => e.RequestMessage.SetHeader("Authorization", _accessToken);
}
}
}
catch (System.Exception ex)
{
Console.WriteLine(String.Format("Error while connecting to https://developer.api.autodesk.com/autocad.io/v2/", ex.Message));
container = null;
throw;
}
}
开发者ID:CADblokeCADforks,项目名称:library-dotnet-autocad.io,代码行数:42,代码来源:AutoCADIOUtilities.cs
示例7: RefreshAsync
/// <summary>
/// 非同步刷新最新資訊
/// </summary>
/// <returns></returns>
public async Task RefreshAsync() {
HttpClient client = new HttpClient();
HtmlDocument HTMLDoc = new HtmlDocument();
HTMLDoc.LoadHtml(await client.GetStringAsync(DataSource));
var script = HTMLDoc.DocumentNode.Descendants("script")
.Where(x => x.InnerHtml?.Length > 0).Select(x => x.InnerHtml).ToArray();
var tempAry = script.First()
.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
.Select((x, i) => new { index = i, item = x })
.GroupBy(x => Math.Floor(x.index / 4.0));
this.LastPassed = null;
this.Delay = new TimeSpan();
foreach (var item in tempAry) {
string[] temp = item.Select(x=>x.item).ToArray();
if(temp[3] == "TRSearchResult.push('x')") {
this.LastPassed = await Station.GetStationByNameAsync(
innerString(temp[0],"'","'")
);
}
}
var time = new TimeSpan(0, int.Parse(innerString(script.Last(), "=", ";")),0);
this.Delay= time;
}
开发者ID:XuPeiYao,项目名称:TwOpenData.Railways,代码行数:32,代码来源:RealTimeTrainInfo.cs
示例8: 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
示例9: Run
public async void Run()
{
var httpClient = new HttpClient();
HttpResponseMessage response = null;
try
{
response = await httpClient.GetAsync(_uri, _cancellationTokenSource.Token);
var remoteStream = await response.Content.ReadAsStreamAsync();
var localStream = await _file.OpenAsync(FileAccess.ReadAndWrite);
//response.Content.Headers.ContentLength;
}
catch (Exception ex)
{
if(Error != null)
Error(this, new DownloadFileErrorArgs(ex, _file));
}
finally
{
if(response != null)
response.Dispose();
}
}
开发者ID:Grawl,项目名称:hubbl,代码行数:25,代码来源:WebFileService.cs
示例10: HttpGet
public static HttpResponseMessage HttpGet(Uri uri)
{
using (var client = new HttpClient())
{
return client.GetAsync(uri).Result;
}
}
开发者ID:kgarsuta,项目名称:iseahorse,代码行数:7,代码来源:HttpHelper.cs
示例11: UpdateContributors
private async void UpdateContributors()
{
try
{
var vms = await Task.Run(async () =>
{
var hc = new HttpClient();
var str = await hc.GetStringAsync(App.ContributorsUrl);
using (var sr = new StringReader(str))
{
var xml = XDocument.Load(sr);
return xml.Root
.Descendants("contributor")
.Where(
e =>
e.Attribute("visible") == null ||
e.Attribute("visible").Value.ToLower() != "false")
.Select(ContributorsViewModel.FromXml)
.ToArray();
}
});
await DispatcherHelper.UIDispatcher.InvokeAsync(
() =>
{
this.Contributors.Clear();
this.Contributors.Add(new ContributorsViewModel("thanks to:", null));
vms.OrderBy(v => v.ScreenName ?? "~" + v.Name)
.ForEach(this.Contributors.Add);
});
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
}
}
开发者ID:R4ndZ-Alice,项目名称:StarryEyes,代码行数:35,代码来源:VersionInfoViewModel.cs
示例12: GetJeuxForainsAsync
public async Task<IList<JeuForain>> GetJeuxForainsAsync()
{
try
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, JEUXFORAINSURL);
HttpClient httpClient = new HttpClient();
HttpResponseMessage httpResponse = await httpClient.SendAsync(request);
string content = await httpResponse.Content.ReadAsStringAsync();
if (!string.IsNullOrEmpty(content))
{
var json = JObject.Parse(content);
var records = Newtonsoft.Json.JsonConvert.DeserializeObject<List<APIJeuxForainsRecord>>(json["records"].ToString());
IList<JeuForain> values = new List<JeuForain>();
foreach (var jeux in records)
values.Add(jeux.Value);
return values;
}
}
catch (Exception ex)
{
Debug.WriteLine("GetJeuxForainsAsync : " + ex);
}
return null;
}
开发者ID:ThierryTournier,项目名称:MVVM-PCL-DI,代码行数:31,代码来源:JeuxForainsAPIOpenDataService.cs
示例13: GetTimelineAsync
public override async Task<List<TimelineData>> GetTimelineAsync()
{
var token = await GetAccessTokenAsync();
var client = new HttpClient { MaxResponseContentBufferSize = 1024 * 1024 };
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var response = await client.GetAsync(string.Format("{0}?screen_name={1}",
StatusesUserTimeline, WebUtility.UrlEncode(ScreenName)));
var json = JsonValue.Parse(await response.Content.ReadAsStringAsync());
var statuses = json.GetArray();
return statuses.Select(status => status.GetObject())
.Select(status =>
{
var text = status.GetNamedString("text");
var user = status.GetNamedObject("user");
var created = status.GetNamedString("created_at");
var name = user.GetNamedString("name");
var screenname = user.GetNamedString("screen_name");
var profileImageUrl = user.GetNamedString("profile_image_url_https");
return new TweetData
{
Title = string.Format("{0} / @{1}", name, screenname),
Body = text,
ImageUri = new Uri(profileImageUrl),
Name = name,
ScreenName = screenname,
CreatedAt = ParseCreatedString(created)
};
})
.Cast<TimelineData>()
.ToList();
}
开发者ID:jpdias,项目名称:StatusUpdate-App,代码行数:34,代码来源:TwitterDownloader.cs
示例14: GetPeople
private static async Task GetPeople(string address)
{
var uriBuilder = new UriBuilder(address);
uriBuilder.Path = "api/Customer";
using (var client = new HttpClient())
{
Console.WriteLine("Getting data without a version...");
var response = await client.GetAsync(uriBuilder.Uri);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());
Console.WriteLine();
Console.WriteLine("Getting data for v1...");
client.DefaultRequestHeaders.Add("api-version", "1");
response = await client.GetAsync(uriBuilder.Uri);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());
Console.WriteLine();
Console.WriteLine("Getting data for v2...");
client.DefaultRequestHeaders.Remove("api-version");
client.DefaultRequestHeaders.Add("api-version", "2");
response = await client.GetAsync(uriBuilder.Uri);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());
Console.WriteLine();
}
}
开发者ID:andreychizhov,项目名称:microsoft-aspnet-samples,代码行数:33,代码来源:Program.cs
示例15: GetSummonersRecentGamesAsync
/// <summary>
/// </summary>
/// <param name="name"></param>
/// <param name="region"></param>
/// <returns>The last 10 games the summoner has played.</returns>
public async Task<List<GameDTO>> GetSummonersRecentGamesAsync(Summoner summoner)
{
if (summoner == null)
{
throw new ArgumentNullException("summoner");
}
if (summoner.ID == 0)
{
throw new ArgumentException("Summoner ID should be a value larger than 0.");
}
string requestPath = string.Format("game/by-summoner/{0}/recent", summoner.ID);
string url = BuildURL(summoner.Region, requestPath);
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(url))
using (HttpContent content = response.Content)
{
string contentStr = await content.ReadAsStringAsync();
GameHistoryDTO gameHistoryDTO = await JsonConvert.DeserializeObjectAsync<GameHistoryDTO>(contentStr);
if (gameHistoryDTO == null)
{
return null;
}
return gameHistoryDTO.games;
}
}
开发者ID:joshlatimer,项目名称:LoLAPIWrapper,代码行数:32,代码来源:GameManager.cs
示例16: CreateHttpClient
public static HttpClient CreateHttpClient()
{
var baseAddress = new Uri("http://localhost:8080");
var config = new HttpSelfHostConfiguration(baseAddress);
// ?
Setup.Configure(config);
var server = new HttpSelfHostServer(config);
var client = new HttpClient(server); // <--- MAGIC!
try
{
client.BaseAddress = baseAddress;
return client;
}
catch
{
client.Dispose();
throw;
}
}
开发者ID:JeffryGonzalez,项目名称:HRSolution,代码行数:25,代码来源:Helpers.cs
示例17: OAuth
public IActionResult OAuth(string code)
{
if (string.IsNullOrEmpty(code))
{
throw new ArgumentException("Invalid parameters");
}
using (var client = new HttpClient())
{
var getTokenUri = this.BuildGetTokenUri(OAuthInfo.ClientId, OAuthInfo.SecretId, OAuthInfo.RedirectedUri, code);
var response = client.GetAsync(getTokenUri);
if (response.Result.IsSuccessStatusCode)
{
string result = response.Result.Content.ReadAsStringAsync().Result;
var resultObjectTemplate = new { ok = false, access_token = string.Empty, error = string.Empty };
var resultObject = JsonConvert.DeserializeAnonymousType(result, resultObjectTemplate);
if (resultObject.ok)
{
this.ViewData["Message"] = $"You Slack token is: {resultObject.access_token}";
}
else
{
this.ViewData["Message"] = $"Unable to retrieve Slack token. Error: {resultObject.error}";
}
}
else
{
throw new Exception(response.Result.ReasonPhrase);
}
}
return this.View();
}
开发者ID:Cocotus,项目名称:Luxa4Slack,代码行数:34,代码来源:DefaultController.cs
示例18: Main
static void Main(string[] args)
{
Console.WriteLine("Username:");
var username = Console.ReadLine();
Console.WriteLine("Password:");
var password = Console.ReadLine();
string uri = "http://localhost:3915/Account/Login";
var client = new HttpClient();
var response = client.PostAsync(uri, new User() { Username = username, Password = password }, new JsonMediaTypeFormatter()).Result;
IEnumerable<string> values;
response.Headers.TryGetValues("Set-Cookie", out values);
if (null == values || string.IsNullOrEmpty(values.First()))
{
Console.WriteLine("Invalid Username or password;");
}
else
{
string newUri = "http://localhost:3915/customer/get/1";
string cookie = values.First();
client.DefaultRequestHeaders.Add("Cookie", cookie);
var getRequestResponse = client.GetAsync(newUri).Result;
Customer customer = getRequestResponse.Content.ReadAsAsync<Customer>().Result;
Console.WriteLine("Customer Id: {0}; Name: {1}", customer.Id, customer.Name);
}
Console.ReadLine();
}
开发者ID:NikolayKostadinov,项目名称:Homeworks,代码行数:30,代码来源:Program.cs
示例19: GeciMeClient
public GeciMeClient()
{
_httpClient = new HttpClient()
{
BaseAddress = new Uri("http://geci.me/api/lyric/")
};
}
开发者ID:sunnycase,项目名称:TomatoMusic,代码行数:7,代码来源:GeciMeClient.cs
示例20: LoadDataFromAPI
public static async Task<string> LoadDataFromAPI(string apiAddress)
{
//method to check if user is authenticated and has valid details
// if invalid details, response message will return unauthorised
var rawAuthInfo = App.validAuthDetails;
var authDetails = JsonConvert.DeserializeObject<ValidAuth>(rawAuthInfo);
var rawData = "";
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(authDetails.token_type, authDetails.access_token);
HttpResponseMessage ResponseMsg = await httpClient.GetAsync(apiAddress);
// check to see if request was successful or not
if (ResponseMsg.StatusCode == System.Net.HttpStatusCode.OK)
{
rawData = await ResponseMsg.Content.ReadAsStringAsync();
}
else if (ResponseMsg.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
rawData = "AuthInvalid";
}
return rawData;
}
开发者ID:ryanch94,项目名称:ThirdYearProject,代码行数:25,代码来源:App.xaml.cs
注:本文中的System.Net.Http.HttpClient类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论