本文整理汇总了C#中System.Net.Http.HttpClient类的典型用法代码示例。如果您正苦于以下问题:C# System.Net.Http.HttpClient类的具体用法?C# System.Net.Http.HttpClient怎么用?C# System.Net.Http.HttpClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
System.Net.Http.HttpClient类属于命名空间,在下文中一共展示了System.Net.Http.HttpClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetHttpClient
public System.Net.Http.HttpClient GetHttpClient()
{
System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
httpClient.BaseAddress = new Uri(@"http://localhost:60736/");
httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
return httpClient;
}
示例2: Execute
public async void Execute(object parameter)
{
var result = Task.FromResult(default(IUICommand));
owner.DownloadVisible = false;
owner.ProgressVisible = true;
var folder = await downloader.VerifyFolderCreation();
using (var client = new System.Net.Http.HttpClient())
{
// find all selected episodes.
List<Task> results = new List<Task>();
foreach (var episode in owner.selectedEpisodes)
{
var path = episode.Description;
var writeTask = downloader.SaveUrlAsync(folder, client, path);
results.Add(writeTask);
}
var allTasks = Task.WhenAll(results.ToArray());
owner.ActiveDownload = allTasks;
try
{
await allTasks;
}
catch (Exception)
{
// Umm, some download failed.
var errMsg = new MessageDialog("One or more downloads failed");
result = errMsg.ShowAsync().AsTask();
}
await result;
}
owner.DownloadVisible = true;
owner.ProgressVisible = false;
owner.selectedEpisodes.Clear();
}
示例3: FromBodyTestAsync
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <exception cref="SwaggerException">A server side error occurred.</exception>
public async System.Threading.Tasks.Task FromBodyTestAsync(GeoPoint location, System.Threading.CancellationToken cancellationToken)
{
var url_ = string.Format("{0}/{1}", BaseUrl, "api/Geo/FromBodyTest");
using (var client_ = new System.Net.Http.HttpClient())
{
var request_ = new System.Net.Http.HttpRequestMessage();
PrepareRequest(client_, ref url_);
var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(location, new Newtonsoft.Json.JsonConverter[] { new Newtonsoft.Json.Converters.StringEnumConverter(), new JsonExceptionConverter() }));
content_.Headers.ContentType.MediaType = "application/json";
request_.Content = content_;
request_.Method = new System.Net.Http.HttpMethod("POST");
request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false);
ProcessResponse(client_, response_);
var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
var status_ = ((int)response_.StatusCode).ToString();
if (status_ == "204")
{
return;
}
else
if (status_ != "200" && status_ != "204")
throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", status_, responseData_, null);
}
}
示例4: OnNavigatedTo
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
date.Text = DateTime.Today.ToString("d.M.yyyy");
System.Net.Http.HttpClient hc = new System.Net.Http.HttpClient();
System.Net.Http.HttpResponseMessage response = await hc.GetAsync("http://api.teknolog.fi/taffa/sv/today/");
response.EnsureSuccessStatusCode();
menu.Text = await response.Content.ReadAsStringAsync();
XmlDocument tileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWide310x150Text05);
XmlNodeList tileTextAttributes = tileXml.GetElementsByTagName("text");
tileTextAttributes[0].InnerText = menu.Text;
XmlDocument squareTileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquare150x150Text03);
XmlNodeList squareTileTextAttributes = squareTileXml.GetElementsByTagName("text");
squareTileTextAttributes[0].AppendChild(squareTileXml.CreateTextNode(menu.Text));
IXmlNode node = tileXml.ImportNode(squareTileXml.GetElementsByTagName("binding").Item(0), true);
tileXml.GetElementsByTagName("visual").Item(0).AppendChild(node);
TileNotification tileNotification = new TileNotification(tileXml);
tileNotification.ExpirationTime = DateTime.Now.Date.AddDays(1);
TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);
}
示例5: Foo
private static async void Foo()
{
Uri uri = new Uri("http://localhost/?cache=1");
System.Net.Http.WebRequestHandler handler =
new System.Net.Http.WebRequestHandler();
// Cache options:
// System.Net.Cache.RequestCacheLevel.BypassCache
// System.Net.Cache.RequestCacheLevel.CacheIfAvailable
handler.CachePolicy = new System.Net.Cache.RequestCachePolicy(
System.Net.Cache.RequestCacheLevel.CacheIfAvailable);
System.Net.Http.HttpClient client2 =
new System.Net.Http.HttpClient(handler);
System.Net.Http.HttpResponseMessage response2 = await client2.GetAsync(uri);
response2.EnsureSuccessStatusCode();
string str = await response2.Content.ReadAsStringAsync();
Console.WriteLine(str);
System.Threading.Thread.Sleep(1111);
response2 = await client2.GetAsync(uri);
response2.EnsureSuccessStatusCode();
str = await response2.Content.ReadAsStringAsync();
Console.WriteLine(str);
autoResetEvent.Set();
}
示例6: OnAuthorization
public override void OnAuthorization(AuthorizationContext filterContext)
{
var username = string.Empty;
if (filterContext.HttpContext.Session["username"] == null)
{
var token = filterContext.HttpContext.Request.QueryString["token"];
if (string.IsNullOrEmpty(token))
{
//先去服务器上获取;
filterContext.Result = new RedirectResult(GetTokenUrl + "?appkey=" + HttpUtility.UrlEncode(AppKey));
}
else
{
username = new System.Net.Http.HttpClient().GetStringAsync(GetUserUrl + "?token=" + token).Result;
if (string.IsNullOrWhiteSpace(username))
{
//跳转到Api登录页
var loginUrl = LoginUrl + "?appkey=" + HttpUtility.UrlEncode(AppKey);
filterContext.Result = new RedirectResult(loginUrl);
}
else
{
filterContext.HttpContext.Session["username"] = username;
}
}
}
//base.OnAuthorization(filterContext);
}
示例7: ProductsAsync
/// <summary>Product Types</summary>
/// <param name="latitude">Latitude component of location.</param>
/// <param name="longitude">Longitude component of location.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>An array of products</returns>
/// <exception cref="SwaggerException">A server side error occurred.</exception>
public async System.Threading.Tasks.Task<System.Collections.ObjectModel.ObservableCollection<Product>> ProductsAsync(double latitude, double longitude, System.Threading.CancellationToken cancellationToken)
{
var url_ = string.Format("{0}/{1}?", BaseUrl, "products");
if (latitude == null)
throw new System.ArgumentNullException("latitude");
else
url_ += string.Format("latitude={0}&", System.Uri.EscapeDataString(latitude.ToString()));
if (longitude == null)
throw new System.ArgumentNullException("longitude");
else
url_ += string.Format("longitude={0}&", System.Uri.EscapeDataString(longitude.ToString()));
using (var client_ = new System.Net.Http.HttpClient())
{
var request_ = new System.Net.Http.HttpRequestMessage();
PrepareRequest(client_, ref url_);
request_.Method = new System.Net.Http.HttpMethod("GET");
request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false);
ProcessResponse(client_, response_);
var responseData_ = await response_.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
var status_ = ((int)response_.StatusCode).ToString();
if (status_ == "200")
{
var result_ = default(System.Collections.ObjectModel.ObservableCollection<Product>);
try
{
if (responseData_.Length > 0)
result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Collections.ObjectModel.ObservableCollection<Product>>(System.Text.Encoding.UTF8.GetString(responseData_, 0, responseData_.Length));
return result_;
}
catch (System.Exception exception)
{
throw new SwaggerException("Could not deserialize the response body.", status_, responseData_, exception);
}
}
else
{
var result_ = default(Error);
try
{
if (responseData_.Length > 0)
result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<Error>(System.Text.Encoding.UTF8.GetString(responseData_, 0, responseData_.Length));
}
catch (System.Exception exception_)
{
throw new SwaggerException("Could not deserialize the response body.", status_, responseData_, exception_);
}
throw new SwaggerException<Error>("Unexpected error", status_, responseData_, result_, null);
}
return default(System.Collections.ObjectModel.ObservableCollection<Product>);
}
}
示例8: GetAsync
protected async Task<System.Net.Http.HttpResponseMessage> GetAsync(string url)
#endif
{
if (url == null) throw new ArgumentNullException(nameof(url));
try
{
var uri = new Uri(url);
#if WINDOWS_PORTABLE || WINDOWS_DESKTOP
using (var client = new System.Net.Http.HttpClient())
#elif WINDOWS_UAP
using (var client = new System.Net.Http.HttpClient())
#endif
{
#if WINDOWS_PORTABLE || WINDOWS_DESKTOP
// Setting timeout for httpclient on portable architecture.
// UAP supports timeout configuration via System.Threading.Task
if (ProxyConfiguration.Timeout.HasValue)
{
client.Timeout = ProxyConfiguration.Timeout.Value;
}
#endif
var response = await client.GetAsync(uri, System.Net.Http.HttpCompletionOption.ResponseContentRead);
if (!response.IsSuccessStatusCode) throw new TheTvDbBadResponseException(response.StatusCode);
return response;
}
}
catch (Exception e)
{
throw new TheTvDbServerNotAvailableException(inner: e);
}
}
示例9: Button_Click_1
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
//http://google.com
//http://countdown.api.tfl.gov.uk/interfaces/ura/instant_V1
//http://countdown.api.tfl.gov.uk/interfaces/ura/instant_V1?StopCode1=52053&DirectionID=1&VisitNumber=1&ReturnList=StopCode1,StopPointName,LineName,DestinationText,EstimatedTime,MessageUUID,MessageText,MessagePriority,MessageType,ExpireTime
//53347 - Queens Avenue towards Archway
var serviceUrl = "http://countdown.api.tfl.gov.uk/interfaces/ura/instant_V1?StopCode1=52053&DirectionID=1&VisitNumber=1&ReturnList=StopCode1,StopPointName,LineName,DestinationText,EstimatedTime,MessageUUID,MessageText,MessagePriority,MessageType,ExpireTime";
var client = new System.Net.Http.HttpClient();
//var responseStream = await client.GetStreamAsync(serviceUrl);
//var reader = new StringReader(responseText);
//while(reader.I.ReadLine())
var responseText = await client.GetStringAsync(serviceUrl);
responseText = responseText.Replace("]", "],");
responseText = string.Format("[{0}]", responseText);
var ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseText));
var serializer = new DataContractJsonSerializer(typeof(object[][]));
var response = (object[][])serializer.ReadObject(ms);
textResult.Text = response.Length.ToString();
}
示例10: UpdateZone
/// <summary>
/// status information to the smart things zone
/// </summary>
/// <param name="zoneInfo"></param>
public static void UpdateZone(ZoneInfo zoneInfo)
{
try
{
OauthInfo authInfo = OauthRepository.Get();
string url = authInfo.endpoints[0].uri + $"/UpdateZone";
var client = new System.Net.Http.HttpClient();
System.Net.Http.HttpRequestMessage msg = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, url);
msg.Headers.Add("Authorization", $"Bearer {authInfo.accessToken}");
List<KeyValuePair<string, string>> parms = new List<KeyValuePair<string, string>>();
parms.Add(new KeyValuePair<string, string>("Id", zoneInfo.Id.ToString()));
parms.Add(new KeyValuePair<string, string>("Status", zoneInfo.Status));
parms.Add(new KeyValuePair<string, string>("Name", zoneInfo.Name));
msg.Content = new System.Net.Http.FormUrlEncodedContent(parms);
var response = client.SendAsync(msg);
response.Wait();
if (response.Result.StatusCode != System.Net.HttpStatusCode.Created)
{
MyLogger.LogError($"Error updating smart things zone {zoneInfo.Id} with status {zoneInfo.Status}");
}
}
catch (Exception ex)
{
MyLogger.LogError($"Error updating smart things zone {zoneInfo.Id} with status {zoneInfo.Status}. Exception was {MyLogger.ExMsg(ex)}");
}
}
示例11: sendRequestAsync
/// <summary>
/// Send a pre-serialized OFX request to the service, retrieve the response and deserialize into an OFX object.
///
/// This is an asycronous call.
/// </summary>
/// <param name="request">Populated OFX request object</param>
/// <returns>The returned task includes a populated OFX response object on successfull call</returns>
public async Task<Protocol.OFX> sendRequestAsync(StreamContent request)
{
// Create an HTTPClient to send the request
using (var client = new System.Net.Http.HttpClient())
{
// OFX endpoints do not use 100 Continue responses. Disable default .NET expectation of them.
client.DefaultRequestHeaders.ExpectContinue = false;
// POST request and await response
var response = await client.PostAsync(m_serviceURI.ToString(), request).ConfigureAwait(false);
// Read into stream
var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
// Deserialize XML stream into object - try directly deserializing
try
{
return (Protocol.OFX) m_serializer.Deserialize(responseStream);
}
catch (System.InvalidOperationException)
{
// This is sometimes thrown when the response is actually UTF-8, but the xml marker claims utf-16
responseStream.Position = 0;
var streamReader = new StreamReader(responseStream, Encoding.UTF8);
return (Protocol.OFX)m_serializer.Deserialize(streamReader);
}
}
}
示例12: Refresh
public async Task<bool> Refresh()
{
if (!RevistaController.Instance.RefreshLista(
await LibHelper.GetHttpPageAsyncHelper(RevistaController.RevistaUrl)))
return false;
var folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(PATHIMAGENS, CreationCollisionOption.OpenIfExists);
if (folder == null)
return false;
using (var http = new System.Net.Http.HttpClient())
{
var ll = await folder.GetFilesAsync();
foreach (var item in Lista.Where(x => ll.FirstOrDefault(y => y.Name.Equals(Path.GetFileName(x.ImgUrl.AbsolutePath))) == null))
{
var file = await folder.CreateFileAsync(Path.GetFileName(item.ImgUrl.AbsolutePath), CreationCollisionOption.ReplaceExisting);
using (var str = await http.GetStreamAsync(item.ImgUrl))
{
str.CopyTo(await file.OpenStreamForWriteAsync());
}
item.ImgUrl = new Uri(file.Path);
}
}
return true;
}
示例13: DetectPublicIP
public async Task<System.Net.IPAddress> DetectPublicIP(int timeoutMs)
{
string url = $"https://api.ipify.org?ticks={System.DateTime.Now.Ticks}";
var client = new System.Net.Http.HttpClient();
client.Timeout = TimeSpan.FromMilliseconds(timeoutMs);
var response = await client.GetStringAsync(url);
return System.Net.IPAddress.Parse(response);
}
示例14:
public async Task ネットからのデータ取得テスト()
{
var client = new System.Net.Http.HttpClient();
var text = await client.GetStringAsync("http://www.yahoo.co.jp/");
// 意図したデータが取得できているかの確認(以下の確認は適当です)
Assert.AreNotEqual(text.Length, 0, "取得したテキストの長さは0にならない");
}
示例15: PostStringAsync2
public async Task<string> PostStringAsync2(string link, List<KeyValuePair<string, string>> values)
{
var httpClient = new System.Net.Http.HttpClient(new System.Net.Http.HttpClientHandler());
System.Net.Http.HttpResponseMessage response = await httpClient.PostAsync(new Uri(link), new System.Net.Http.FormUrlEncodedContent(values));
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
System.Diagnostics.Debug.WriteLine(response.Headers);
return responseString;
}