从HTTP响应中获取结果

时间:2013-04-17 12:57:12

标签: c# httpwebrequest httpwebresponse

我有以下C#类,它启动从Windows Phone到服务器的HTTP请求:

public class Request
{
    public string data;
    public string result;

    public Request()
    {

    }

    public void doRequest(string parameters, string URL)
    {
        data = parameters;

        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
    }

    public void GetRequestStreamCallback(IAsyncResult callbackResult)
    {
        HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
        Stream postStream = myRequest.EndGetRequestStream(callbackResult);
        byte[] byteArray = Encoding.UTF8.GetBytes(data);

        postStream.Write(byteArray, 0, byteArray.Length);
        postStream.Close();

        myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), myRequest);
    }

    public void GetResponsetStreamCallback(IAsyncResult callbackResult)
    {
        HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);

        StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream());
        result = httpWebStreamReader.ReadToEnd();
    }

现在,在我的主类中,我调用doRequest方法从Windows Phone执行HTTP请求:

Request req = new Request();
req.doRequest("function=LogIn&username=" + username + "&password=" + password, "http://localhost:4000/Handler.ashx");

调用此方法时,如何从服务器获取结果(结果变量),因为它是在GetResponsetStreamCallback方法中而不是在doRequest方法中接收的?

1 个答案:

答案 0 :(得分:0)

你有几种可能性。一种方法是定义property以使结果可在外部访问。定义

public class Request
{
    public string Result
    {
      get{ 
           if(result != null && !string.IsNullOrEmpty(result))
                return result;
           return null;
         }
    }
  ...
}

您可以创建一个事件并让对象订阅它,这样您就可以在异步请求结束时注意到它们。或者让您的呼叫同步,这样做更容易,因为您没有同步您的呼叫和来自其他对象的请求。