非同步的HTTP POST與GET請求例子
Get方法:
private void HttpGet()
{
WebClient wc = new WebClient();
Uri uri = new Uri("http://localhost:3881/Financial.ashx?ticker=NTES&startdate=1-1-2009&enddate=9-2-2010", UriKind.RelativeOrAbsolute);
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
wc.OpenReadAsync(uri);
}
private void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
StreamReader read = new StreamReader(e.Result);
string strXML = read.ReadToEnd();
XDocument xmlDoc = XDocument.Parse(strXML);
IEnumerable<TimeSeriesData> myTimeSeries = from item in xmlDoc.Descendants("TimeSeries")
select new TimeSeriesData()
{
open = Convert.ToDouble(item.Element("Open").Value),
close = Convert.ToDouble(item.Element("Close").Value),
high = Convert.ToDouble(item.Element("High").Value),
low = Convert.ToDouble(item.Element("Low").Value),
adjclose = Convert.ToDouble(item.Element("AdjClose").Value),
volume = Convert.ToDouble(item.Element("Volume").Value),
date = Convert.ToDateTime(item.Element("Date").Value)
};
TimeSeries.ItemsSource = myTimeSeries;
}
Post方法:
private void HttpPost()
{
Uri uri = new Uri("http://localhost:3881/Financial.ashx");
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.BeginGetRequestStream(new AsyncCallback(RequestProceed),request);
}
private void RequestProceed(IAsyncResult asyncResult)
{
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
StreamWriter postDataWriter = new StreamWriter(request.EndGetRequestStream(asyncResult));
postDataWriter.Write("ticker=NTES");
postDataWriter.Write("&startdate=1-1-2009");
postDataWriter.Write("&enddate=9-2-2010");
postDataWriter.Close();
request.BeginGetResponse(new AsyncCallback(ResponesProceed),request);
}
private void ResponesProceed(IAsyncResult asyncResult)
{
WebRequest request = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse response=(HttpWebResponse)request.EndGetResponse(asyncResult);
StreamReader responseReader = new StreamReader(response.GetResponseStream());
string responseString = responseReader.ReadToEnd();
XDocument xmlDoc = XDocument.Parse(responseString);
IEnumerable<TimeSeriesData> myTimeSeries = from item in xmlDoc.Descendants("TimeSeries")
select new TimeSeriesData()
{
open = Convert.ToDouble(item.Element("Open").Value),
close = Convert.ToDouble(item.Element("Close").Value),
high = Convert.ToDouble(item.Element("High").Value),
low = Convert.ToDouble(item.Element("Low").Value),
adjclose = Convert.ToDouble(item.Element("AdjClose").Value),
volume = Convert.ToDouble(item.Element("Volume").Value),
date = Convert.ToDateTime(item.Element("Date").Value)
};
Dispatcher.BeginInvoke(()=>TimeSeries.ItemsSource=myTimeSeries);
}