本文整理汇总了C#中System.Net.Http.HttpClient类的典型用法代码示例。如果您正苦于以下问题:C# HttpClient类的具体用法?C# HttpClient怎么用?C# HttpClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HttpClient类属于System.Net.Http命名空间,在下文中一共展示了HttpClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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();
}
}
示例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);
}
}
示例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);
}
示例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);
}
示例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));
}
}
示例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;
}
}
示例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;
}
示例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");
}
示例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();
}
}
示例10: HttpGet
public static HttpResponseMessage HttpGet(Uri uri)
{
using (var client = new HttpClient())
{
return client.GetAsync(uri).Result;
}
}
示例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);
}
}
示例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;
}
示例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();
}
示例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();
}
}
示例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;
}
}