本文整理汇总了C#中System.Net.Http.HttpClient.Wait方法的典型用法代码示例。如果您正苦于以下问题:C# HttpClient.Wait方法的具体用法?C# HttpClient.Wait怎么用?C# HttpClient.Wait使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Http.HttpClient
的用法示例。
在下文中一共展示了HttpClient.Wait方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: FinishGame
public static GameFinishResult FinishGame(bool? isFullGame, bool? isDraw, string channel, params GameFinishPlayerInfo[] playerInfos)
{
try
{
if (GameID == null || GameSecret == null)
new GameFinishResult { Error = new Exception("Please set GameID & GameSecret") };
var gameInfo = new GameFinishInfo
{
GameID = GameID.Value,
GameSecret = GameSecret,
IsFull = isFullGame,
IsDraw = isDraw,
Channel = channel,
Players = playerInfos.ToList()
};
var url = String.Format(FinishGameUrl, GameID);
var postTask = new HttpClient().PostAsJsonAsync<GameFinishInfo>(url, gameInfo);
postTask.Wait();
if (postTask.IsCompleted && postTask.Result.StatusCode == System.Net.HttpStatusCode.OK)
{
var resultTask = postTask.Result.Content.ReadAsAsync<GameFinishResult>();
resultTask.Wait();
if (!resultTask.IsCompleted)
{
return new GameFinishResult { Error = resultTask.Exception };
}
return resultTask.Result;
}
return new GameFinishResult { Error = postTask.Exception };
}
catch (Exception ex)
{
return new GameFinishResult { Error = ex };
}
}
示例2: Download
/// <summary>
/// Get data in this.Url and use <paramref name="fileWriter"/> to save to disk
/// </summary>
/// <param name="fileWriter"></param>
/// <returns>Task that completes when file is written to disk</returns>
public Task<string> Download(IFileWriter fileWriter)
{
var tId = Thread.CurrentThread.ManagedThreadId;
try
{
var contentsTask = new HttpClient().GetStringAsync(Url);
//Block current thread until contentsTask is complete
contentsTask.Wait();
//Return task that will write the contents to disk
return fileWriter.WriteFile(contentsTask.Result, Name);
}
catch
{
//Return a sucessfully completed Task<string> with the below result
return Task.FromResult(string.Format("Failed to download: {0}", Url));
}
}
示例3: ShortenUrlAsync
/// <summary>
/// Shortens a url
/// </summary>
/// <param name="url">Url to shorten</param>
/// <returns>The id of the shortened url</returns>
public async Task<int> ShortenUrlAsync(string url)
{
url = DefaultToHttpsProtocol(url);
var uri = new Uri(url, UriKind.RelativeOrAbsolute);
var request = new HttpClient().GetAsync(uri.ToString());
var shortUrl = ShortenedUrls.Create();
shortUrl.Created = DateTime.UtcNow;
shortUrl.Url = uri.ToString();
ShortenedUrls.Add(shortUrl);
if (request.Wait(2000))
{
shortUrl.HttpStatusCode = (int)request.Result.StatusCode;
if (request.Result.IsSuccessStatusCode)
{
var response = await request.Result.Content.ReadAsStringAsync();
shortUrl.Title = GetTitle(response);
}
}
await SaveChangesAsync();
return shortUrl.Id;
}
示例4: FakeServer_IgnoredParameter_Returns200
public void FakeServer_IgnoredParameter_Returns200()
{
var expectedResult = new { ResourceId = 1234 };
const string baseAddress = "http://localhost:12354";
const string fakeurl = "/some-resource/{ignore}/some-resource?date={ignore}&type={ignore}";
const string actualurl = "/some-resource/1234/some-resource?date=2015-02-06T09:52:10&type=1";
using (var fakeServer = new FakeServer(12354))
{
fakeServer.Expect.Get(fakeurl).Returns(HttpStatusCode.Accepted, expectedResult);
fakeServer.Start();
var t = new HttpClient().GetAsync(new Uri(baseAddress + actualurl));
t.Wait();
var result = t.Result;
result.StatusCode.Should().Be(HttpStatusCode.Accepted);
}
}
示例5: FakeServer_ExpectPutWithObjectBodyReturns201_Returns201
public void FakeServer_ExpectPutWithObjectBodyReturns201_Returns201()
{
var expectedResult = new {RestaurantId = 1234};
const string baseAddress = "http://localhost:12354";
const string url = "/some-url";
using (var fakeServer = new FakeServer(12354))
{
fakeServer.Expect.Put(url, string.Empty).Returns(HttpStatusCode.Created, expectedResult);
fakeServer.Start();
var t = new HttpClient().PutAsync(new Uri(baseAddress + url), new StringContent(String.Empty));
t.Wait();
var result = t.Result;
result.StatusCode.Should().Be(HttpStatusCode.Created);
}
}
示例6: FakeServer_ExpectPutWithComplexBodyReturnsComplexObject
public void FakeServer_ExpectPutWithComplexBodyReturnsComplexObject()
{
const string expectedResult = "{\"Complex\":{\"Property1\":1,\"Property2\":true}}";
const string body = "{\"Complex\":1}";
using (var fakeServer = new FakeServer(12354))
{
fakeServer.Expect.Put("/some-url", body).Returns(HttpStatusCode.Created, expectedResult);
fakeServer.Start();
var t = new HttpClient().PutAsync(new Uri("http://localhost:12354" + "/some-url"), new StringContent(body));
t.Wait();
var result = t.Result;
var resultTask = result.Content.ReadAsStringAsync();
resultTask.Wait();
result.StatusCode.Should().Be(HttpStatusCode.Created);
resultTask.Result.Should().Be(expectedResult);
}
}
示例7: FakeServer_ExpectGetToAnEndpointWithAFiveSecondResponseTime_ResponseTimeIsGreaterThanFiveSeconds
public void FakeServer_ExpectGetToAnEndpointWithAFiveSecondResponseTime_ResponseTimeIsGreaterThanFiveSeconds()
{
var expectedResult = new { ResourceId = 1234 };
const string baseAddress = "http://localhost:12354";
var expectedResponseTime = TimeSpan.FromSeconds(5);
const string fakeurl = "/some-url";
using (var fakeServer = new FakeServer(12354))
{
fakeServer.Expect.ResponseTime = expectedResponseTime;
fakeServer.Expect.Get(fakeurl).Returns(HttpStatusCode.OK, expectedResult);
fakeServer.Start();
var stopwatch = Stopwatch.StartNew();
var t = new HttpClient().GetAsync(new Uri(baseAddress) + fakeurl);
t.Wait();
stopwatch.Stop();
stopwatch.Elapsed.Should().BeGreaterOrEqualTo(expectedResponseTime);
}
}
示例8: updateData
public bool updateData() {
SQLiteConnection connection = DependencyService.Get<IDatabaseHandler>().getDBConnection();
Info cacheInfo = connection.Table<Info>().Where(i => i.key.Equals("eventCacheTime")).FirstOrDefault();
long lastCacheTime = cacheInfo.value;
long currentTime = (long)(DateTime.Now - new DateTime(1970, 1, 1)).TotalMilliseconds;
if (currentTime - lastCacheTime > 1000 * 60 * 60 * 6) {
string html;
Task<string> task = new HttpClient().GetStringAsync(new Uri("http://harrisburg.psu.edu/calendar"));
task.Wait();
html = task.Result;
for (int i = 1; i < 9; i++) {
Task<string> task2 = new HttpClient().GetStringAsync(new Uri("http://harrisburg.psu.edu/calendar?page=" + i));
task2.Wait();
html += task2.Result;
}
string regex = @"views-row-\d.*?<span class=""date-display-start""><span>(\w{3})\s(\d{4}).*?<\/time>\s*(<span class=""separator"">.*?<div class=""clr""><\/div>|<div class=""clr""><\/div>)<\/span>.*?<span class=""field-content""><a href=""([\/\w\d\-]*)"">(.*?)<\/a><\/span>";
List<Event> events = new List<Event>();
MatchCollection matches = Regex.Matches(html, regex, RegexOptions.Singleline);
foreach (Match m in matches) {
Event e = new Event(System.Net.WebUtility.HtmlDecode(m.Groups[5].Value), m.Groups[1].Value, m.Groups[2].Value, "http://harrisburg.psu.edu" + m.Groups[4].Value);
if (!events.Contains(e))
events.Add(e);
}
connection.BeginTransaction();
connection.DeleteAll<Event>();
foreach (Event e in events) {
connection.Insert(e);
}
cacheInfo.value = currentTime; //Not entirely accurate, but will work alright
connection.Update(cacheInfo);
connection.Commit();
connection.Close();
updateData();
} else if (event_picker.Items.Count == 0) {
var eventEntries = connection.Table<Event>();
event_picker.Items.Clear();
foreach (var e in eventEntries) {
string month = e.month + " " + e.year;
if (!event_picker.Items.Contains(month))
event_picker.Items.Add(month);
}
connection.Close();
string now = numberToMonth(DateTime.Now.Month) + " " + DateTime.Now.Year;
for (int i = 0; i < event_picker.Items.Count; i++) {
if (event_picker.Items[i].Equals(now)) {
event_picker.SelectedIndex = i;
break;
}
}
if (event_picker.SelectedIndex == -1 && event_picker.Items.Count > 0)
event_picker.SelectedIndex = 0;
}
return false;
}
示例9: SendAsync_ServiceModel_Throws_When_StreamContent_Throws
public void SendAsync_ServiceModel_Throws_When_StreamContent_Throws(string uri, TransferMode transferMode)
{
// Arrange
server = CreateServer(transferMode);
Task task = new HttpClient().GetAsync(BaseUri(transferMode) + uri);
// Act & Assert
Assert.Throws<HttpRequestException>(() => task.Wait());
}
示例10: SendAsync_ServiceModel_Closes_Connection_When_ObjectContent_CopyToAsync_Throws
public void SendAsync_ServiceModel_Closes_Connection_When_ObjectContent_CopyToAsync_Throws(string uri, TransferMode transferMode)
{
// Arrange
server = CreateServer(transferMode);
Task<HttpResponseMessage> task = new HttpClient().GetAsync(BaseUri(transferMode) + uri);
// Act & Assert
Assert.Throws<HttpRequestException>(() => task.Wait());
}
示例11: SendAsync_ServiceModel_Throws_When_StreamContent_Throws
public void SendAsync_ServiceModel_Throws_When_StreamContent_Throws(string uri)
{
// Arrange
Task task = new HttpClient(_server).GetAsync(((AzureServiceBusConfiguration)_server.Configuration).BaseAddress + uri);
// Act & Assert
Assert.Throws<InvalidOperationException>(() =>
{
try
{
task.Wait();
}
catch (Exception e)
{
throw e.InnerException;
}
});
}
示例12: SendAsync_ServiceModel_Closes_Connection_When_ObjectContent_CopyToAsync_Throws
public void SendAsync_ServiceModel_Closes_Connection_When_ObjectContent_CopyToAsync_Throws(string uri)
{
// Arrange
Task<HttpResponseMessage> task = new HttpClient(_server).GetAsync(((AzureServiceBusConfiguration)_server.Configuration).BaseAddress + uri);
// Act & Assert
Assert.Throws<InvalidOperationException>(() =>
{
try
{
task.Wait();
}
catch (Exception e)
{
throw e.InnerException;
}
});
}
示例13: GetUser
public static JokUserInfo GetUser(string token, string ipaddress)
{
try
{
var url = String.Format(GetUserUrl, token, ipaddress);
var t = new HttpClient().GetStringAsync(url);
t.Wait();
return JsonConvert.DeserializeObject<JokUserInfo>(t.Result);
}
catch
{
return new JokUserInfo();
}
}