如何使用Windows Phone 8进行HttpClient POST?它只是挂起 [英] How can I do HttpClient POST with Windows Phone 8 ? It just hangs
问题描述
我获得了Winodws Phone 8的webapi.client的alpha版本,下面的代码在请求后挂起..我做错了什么?
I got the alpha of webapi.client for Winodws Phone 8 and the code below hangs after the request.. am I doing something wrong ?
var client = new HttpClient();
client.BaseAddress = new Uri("http://punkoutersoftware.azurewebsites.net");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var score = new DrunkMeterScore() { Name = "Joe", Score = 2.67 };
//MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();
//HttpContent content = new ObjectContent<DrunkMeterScore>(score, jsonFormatter);
//var resp = client.PostAsync("api/DrunkMeterScore", content).Result;
//Uri scoreUri = null;
//HttpResponseMessage response = client.PostAsJsonAsync("api/DrunkMeterScore", score).Result;
//if (response.IsSuccessStatusCode)
//{
// scoreUri = response.Headers.Location;
//}
//else
//{
// Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
//}
如果你做SharePoint开发并让MSN加我! punkouter@hotmail.com我们可以互相帮助。我的SharePoint博客---> http://punkouter.spaces.live.com/
If you do SharePoint dev and have MSN add me!! punkouter@hotmail.com We can help each other out. My SharePoint Blog ---> http://punkouter.spaces.live.com/
推荐答案
目前尚不清楚您提供的代码如何被调用&NBSP;借用其他一些代码,我可能会沿着以下几点做一些事情:
It is not clear from what you provided how this code is getting called. Borrowing from some other code, I would probably do something along these lines:
public sealed class Class1 : IDisposable
{
static readonly Tuple<bool, Uri> NoAnswer = new Tuple<bool, Uri>(false, null);
readonly HttpClient _client = new HttpClient
{
BaseAddress = new Uri("http://punkoutersoftware.azurewebsites.net")
};
public Class1()
{
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
#region IDisposable Members
public void Dispose()
{
if (null != _client)
_client.Dispose();
}
#endregion
public async Task DoStuff(CancellationToken cancellationToken)
{
var score = new DrunkMeterScore
{
Name = "Joe",
Score = 2.67
};
var scoreUri = await Retries.Retry((lastTry, ct) => PostScore(score, ct, lastTry), cancellationToken).ConfigureAwait(false);
Debug.WriteLine("Got " + scoreUri);
}
async Task<Tuple<bool, Uri>> PostScore(DrunkMeterScore score, CancellationToken cancellationToken, bool isLastTry)
{
using (var response = await _client.PostAsJsonAsync("api/DrunkMeterScore", score, cancellationToken).ConfigureAwait(false))
{
if (response.IsSuccessStatusCode)
return Tuple.Create(true, response.Headers.Location);
// Don't retry 404s.
if (isLastTry || response.StatusCode == HttpStatusCode.NotFound)
response.EnsureSuccessStatusCode();
}
return NoAnswer;
}
}
其中Retries如下所示:
Where Retries looks like this:
static class Retries
{
public static async Task<T> Retry<T>(Func<bool, CancellationToken, Task<Tuple<bool, T>>> callback, CancellationToken cancellationToken)
{
var delay = 1000;
for (var retry = 2; retry >= 0; --retry)
{
var isLastTry = 1 == retry;
try
{
var result = await callback(isLastTry, cancellationToken);
if (result.Item1)
return result.Item2;
}
catch (TaskCanceledException)
{
if (isLastTry || cancellationToken.IsCancellationRequested)
throw;
// Some network timeout has happened; ignore it and try again.
}
catch (AggregateException aggregateException)
{
if (isLastTry || cancellationToken.IsCancellationRequested)
throw;
aggregateException.Handle(ex => ex is TaskCanceledException);
}
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
delay *= 2;
}
throw new TimeoutException("...something constructive...");
}
}
然后使用类似的东西:
public partial class MainPage : PhoneApplicationPage
{
readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
readonly Class1 _class1;
// Constructor
public MainPage()
{
InitializeComponent();
_class1 = new Class1();
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
async void Button1_Click(object sender, RoutedEventArgs e)
{
Button1.IsEnabled = false;
try
{
await _class1.DoStuff(_cancellationTokenSource.Token);
}
finally
{
Button1.IsEnabled = true;
}
}
}
这篇关于如何使用Windows Phone 8进行HttpClient POST?它只是挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!