Non so come organizzare il mio codice. Proprio ora ho scaricato tutto in MainPage per il test. Ma qual è il modo corretto per gestire il recupero dei dati dal servizio web REST in Windows Phone 8? Ho più pagine che devono utilizzare i dati che vengono restituiti.
/// <summary>
/// State information for our BeginGetResponse async call
/// </summary>
public class UpdateState
{
public HttpWebRequest AsyncRequest { get; set; }
public HttpWebResponse AsyncResponse { get; set; }
}
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
private async void test()
{
var handler = new HttpClientHandler();
if (handler.SupportsAutomaticDecompression)
{
handler.AutomaticDecompression = DecompressionMethods.GZip |
DecompressionMethods.Deflate;
}
// form the URI
UriBuilder fullUri = new UriBuilder("http://test/GetData?");
fullUri.Query = "format=xml¶m=test&dateFrom=20071225&dateTo=20080101";
var httpClient = new HttpClient(handler);
var str = await httpClient.GetStringAsync(fullUri.Uri);
string test = "";
}
private void Button_Click(object sender, RoutedEventArgs e)
{
test();
// form the URI
UriBuilder fullUri = new UriBuilder("http://test/GetData?");
fullUri.Query = "format=xml¶m=test&dateFrom=20140124&dateTo=201425 ";
// initialize a new WebRequest
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fullUri.Uri);
// set up the state object for the async request
UpdateState state = new UpdateState();
state.AsyncRequest = request;
// start the asynchronous request
request.BeginGetResponse(new AsyncCallback(HandleResponse),
state);
}
/// <summary>
/// Handle the information returned from the async request
/// </summary>
/// <param name="asyncResult"></param>
private void HandleResponse(IAsyncResult asyncResult)
{
// get the state information
UpdateState forecastState = (UpdateState)asyncResult.AsyncState;
HttpWebRequest forecastRequest = (HttpWebRequest)forecastState.AsyncRequest;
// end the async request
forecastState.AsyncResponse = (HttpWebResponse)forecastRequest.EndGetResponse(asyncResult);
Stream streamResult;
string newCredit = "";
string newCityName = "";
int newHeight = 0;
string XMLresult = string.Empty;
try
{
// get the stream containing the response from the async call
string type = forecastState.AsyncResponse.ContentType;
streamResult = forecastState.AsyncResponse.GetResponseStream();
XMLresult = getXMLData(streamResult);
// load the XML
XElement xmlData = XElement.Parse(XMLresult);
string t = "";
}
catch (FormatException)
{
// there was some kind of error processing the response from the web
// additional error handling would normally be added here
return;
}
}