简体   繁体   English

WP7使用POST方法创建帮助程序类以便于使用HttpWebRequest

[英]WP7 Create helper class for easy use HttpWebRequest with POST method

Actually I have something like this: 其实我有这样的事情:

private void createHttpRequest()
    {
        System.Uri myUri = new System.Uri("..url..");
        HttpWebRequest myHttpRequest = (HttpWebRequest)HttpWebRequest.Create(myUri);
        myHttpRequest.Method = "POST";
        myHttpRequest.ContentType = "application/x-www-form-urlencoded";
        myHttpRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myHttpRequest);
    }

void GetRequestStreamCallback(IAsyncResult callbackResult)
    {
        HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
        // End the stream request operation
        Stream postStream = myRequest.EndGetRequestStream(callbackResult);

        string hash = HashHelper.createStringHash("123", "TEST", "0216");
        // Create the post data
        byte[] byteArray = createByteArrayFromHash(hash);

        // Add the post data to the web request
        postStream.Write(byteArray, 0, byteArray.Length);
        postStream.Close();

        // Start the web request
        myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), myRequest);
    }

 void GetResponsetStreamCallback(IAsyncResult callbackResult)
    {
        HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
        using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
        {
            string result = httpWebStreamReader.ReadToEnd();
            ApiResponse apiResponse = (ApiResponse)JsonConvert.DeserializeObject<ApiResponse>(result);
        }
    }

It's good, it's working but now I must use these methods in every page and just change method createByteArrayFromHash which creates request. 它很好,它正在工作,但现在我必须在每个页面中使用这些方法,只需更改创建请求的方法createByteArrayFromHash。 What if I want to create helper class that can help me to do this in something about 3 lines of code in page. 如果我想创建帮助程序类,可以帮助我在页面中的3行代码中执行此操作,该怎么办? How would you do that? 你会怎么做? I was thinking about this way but how to add request before response? 我正在考虑这种方式,但如何在响应之前添加请求? Or would you do it another way? 或者你会以另一种方式做到吗? Thanks 谢谢

Yeah, it's better to use async and await . 是的,最好使用asyncawait Here is an example of such a wrapper: 这是一个这样的包装器的例子:

public async Task<string> SendRequestGetResponse(string postData, CookieContainer cookiesContainer = null)
{
    var postRequest = (HttpWebRequest)WebRequest.Create(Constants.WebServiceUrl);
    postRequest.ContentType = "Your content-type";
    postRequest.Method = "POST";
    postRequest.CookieContainer = new CookieContainer();
    postRequest.CookieContainer = App.Session.Cookies;

    using (var requestStream = await postRequest.GetRequestStreamAsync())
    {
        byte[] postDataArray = Encoding.UTF8.GetBytes(postData);
        await requestStream.WriteAsync(postDataArray, 0, postDataArray.Length);
    }

    var postResponse = await postRequest.GetResponseAsync() as HttpWebResponse;

    if (postResponse != null)
    {
        var postResponseStream = postResponse.GetResponseStream();
        var postStreamReader = new StreamReader(postResponseStream);

        // Can use cookies if you need
        if (cookiesContainer == null)
        {
            if (!string.IsNullOrEmpty(postResponse.Headers["YourCookieHere"]))
            {
                var cookiesCollection = postResponse.Cookies;
                // App.Session is a global object to store cookies and etc.
                App.Session.Cookies.Add(new Uri(Constants.WebServiceUrl), cookiesCollection);
            }
        }

        string response = await postStreamReader.ReadToEndAsync();
        return response;
    }
    return null;
}

You can modify it as you wish 您可以根据需要进行修改

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM