原文:
windows phone 7 通过Post提交URL到服务器,从服务器获取数据(比如登陆时候使用)
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(UrlManager.Login()); myRequest.Method = "POST"; myRequest.ContentType = "application/x-www-form-urlencoded"; myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest); private void GetRequestStreamCallback(IAsyncResult asynchronousResult) { HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; System.IO.Stream postStream = request.EndGetRequestStream(asynchronousResult); // Prepare Parameters String string parametersString = "username=用户名&password=密码"; //foreach (KeyValuePair<string, string> parameter in parameters) //{ // parametersString = parametersString + (parametersString != "" ? "&" : "") + string.Format("{0}={1}", parameter.Key, parameter.Value); //} byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(parametersString); // Write to the request stream. postStream.Write(byteArray, 0, parametersString.Length); postStream.Close(); // Start the asynchronous operation to get the response request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request); } private void GetResponseCallback(IAsyncResult asynchronousResult) { HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult); Stream streamResponse = response.GetResponseStream(); StreamReader streamRead = new StreamReader(streamResponse); string responseString = streamRead.ReadToEnd(); // Close the stream object streamResponse.Close(); streamRead.Close(); }