我有一個httpWebRequest來訪問XML並將其保存到本地,然後將其讀取並顯示到屏幕上。問題是,我有一個以上的「樞紐項目」做到這一點,而且節省了XML的方法是將變量推入方法
private static void GetResponseCallback(IAsyncResult asynchronousResult)
,不支持增加一個新的變量,所以我可以動態命名XML (「tmp」+ xmlName +「。xml」)。
所以問題是:我如何推送一個變量在XML名稱?
public class HttpWebReqMethod
{
public void httpRequestMethod (string url, string xmlName)
{
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.ContentType = "text/xml";
httpRequest.Method = "POST";
httpRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), httpRequest);
}
private static void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest httpRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
Stream postStream = httpRequest.EndGetRequestStream(asynchronousResult);
string postData = "";
// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Write to the request stream.
postStream.Write(byteArray, 0, postData.Length);
postStream.Close();
// Start the asynchronous operation to get the response
httpRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), httpRequest);
}
private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest httpRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
HttpWebResponse response = (HttpWebResponse)httpRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseStream = streamRead.ReadToEnd();
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var istream = new IsolatedStorageFileStream(@"tmp" + xmlName + ".xml", FileMode.OpenOrCreate, store))
{
using (var sw = new StreamWriter(istream))
{
sw.Write(responseStream);
}
}
}
// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
}
哦,我看到rudi_visser選擇了第二個選項,並解釋它更好的:)還有第三個是一個很好的和對於某些場景可能非常有用。 – TDaver
你能幫我打回「工廠」嗎?我得到:GetResponseCallback(字符串)'返回void,一個返回關鍵字不能跟在一個對象表達式 – observ
請注意,我已經更改了SIGNATURE ... – TDaver