0
我有一個主頁,在那裏我調用一個讀取JSON與異步方法的類,這種方法很好,但我需要返回JSON的值到主頁面。異步方法的返回值
MainPage.cs,
private void btnPrueba_Click(object sender, RoutedEventArgs e)
{
Dictionary<string,string> parametros = new Dictionary<string,string>();
parametros.Add("login", "12345678R");
parametros.Add("password", "123123");
objPrueba = new prueba();
objPrueba.doPost("http://prueba.es/login", parametros);
}
類Post.cs,
public void doPost(string url, Dictionary<string, string> parametros)
{
System.Uri myUri = new System.Uri(url);
HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(myUri);
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
//relleno variable con los parametros
foreach (KeyValuePair<string, string> D in parametros)
{
parametrosData = parametrosData + D.Key + "=";
parametrosData = parametrosData + D.Value + "&";
}
bool a = myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest).IsCompleted;
string b = "1231232";
}
void GetRequestStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
// End the stream request operation
Stream postStream = myRequest.EndGetRequestStream(callbackResult);
// Create the post data
string postData = parametrosData;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
myRequest.BeginGetResponse(new System.AsyncCallback(GetResponsetStreamCallback), myRequest);
}
void GetResponsetStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackRe sult);
using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
{
string result = httpWebStreamReader.ReadToEnd();
//For debug: show results
Debug.WriteLine(result);
//RETURN VALUE result TO MAINPAGE.CS
}
}
1 )在發出Web請求時,您應該使用「WebClient」來執行基於異步的任務。 2)格式化您的代碼,只需在VS中格式化它,然後將其複製到SO。 – Servy