如何在Windows Phone 7中的每个请求之前发送预请求

时间:2015-02-28 05:15:11

标签: windows-phone-7 httprequest

我想在发送每个请求之前向我的服务器发送一个预先请求。从那个预先请求我将收到来自我的服务器的令牌,而不是我必须将该令牌添加到所有请求中。这是一个过程。

我尝试了一些方法来实现这一目标。但我面临一个问题。也就是说,当我尝试发送预请求时,它正在处理当前请求。这意味着两个请求并行。

我想先发送预请求并解析响应。解析预请求响应后,我只想发送另一个请求。但首先请求不等待预请求响应。请允许我以任何方式在所有请求之前发送预请求。

这是我的代码:

视图模型:

`public class ListExampleViewModel
    {
        SecurityToken sToken = null;
        public ListExampleViewModel()
        {
            GlobalConstants.isGetToken = true;
            var listResults = REQ_RESP.postAndGetResponse((new ListService().GetList("xx","xxx")));

            listResults.Subscribe(x =>
            {
                Console.WriteLine("\n\n..................................2");
                Console.WriteLine("Received Response==>" + x);
            });
        }
    }`

请求和响应的常量类:

`public class REQ_RESP
    {
        private static string receivedAction = "";
        private static string receivedPostDate = "";


        public static IObservable<string> postAndGetResponse(String postData)
        {
            if (GlobalConstants.isGetToken)
            {
    //Pre Request for every reusest               
                receivedPostDate = postData;
                GlobalConstants.isGetToken = false;
                getServerTokenMethod();
                postData = receivedPostDate;
            }

            HttpWebRequest serviceRequest =
            (HttpWebRequest)WebRequest.Create(new Uri(Constants.SERVICE_URI));


            var fetchRequestStream =
                 Observable.FromAsyncPattern<Stream>(serviceRequest.BeginGetRequestStream,
                                                                 serviceRequest.EndGetRequestStream);
            var fetchResponse =
                Observable.FromAsyncPattern<WebResponse>(serviceRequest.BeginGetResponse,
                                                            serviceRequest.EndGetResponse);

            Func<Stream, IObservable<HttpWebResponse>> postDataAndFetchResponse = st =>
            {
                using (var writer = new StreamWriter(st) as StreamWriter)
                {
                    writer.Write(postData);
                    writer.Close();
                }
                return fetchResponse().Select(rp => (HttpWebResponse)rp);
            };

            Func<HttpWebResponse, IObservable<string>> fetchResult = rp =>
            {
                if (rp.StatusCode == HttpStatusCode.OK)
                {

                    using (var reader = new StreamReader(rp.GetResponseStream()))
                    {
                        string result = reader.ReadToEnd();
                        reader.Close();
                        rp.GetResponseStream().Close();
                        XDocument xdoc = XDocument.Parse(result);
                        Console.WriteLine(xdoc);
                        return Observable.Return<string>(result);
                    }
                }
                else
                {
                    var msg = "HttpStatusCode == " + rp.StatusCode.ToString();
                    var ex = new System.Net.WebException(msg,
                        WebExceptionStatus.ReceiveFailure);
                    return Observable.Throw<string>(ex);
                }

            };

            return
                from st in fetchRequestStream()
                from rp in postDataAndFetchResponse(st)
                from str in fetchResult(rp)
                select str;
        }

        public static void getServerTokenMethod()
        {
            SecurityToken token = new SecurityToken();

            var getTokenResults = REQ_RESP.postAndGetResponse((new ServerToken().GetServerToken()));

            getTokenResults.Subscribe(x =>
            {
                ServerToken serverToken = new ServerToken();
                ServiceModel sm = new ServiceModel();
    //Parsing Response
                serverToken = extract(x, sm);
                if (!(string.IsNullOrEmpty(sm.NetErrorCode)))
                {
        MessageBox.Show("Show Error Message");
                }
                else
                {
                    Console.WriteLine("\n\n..................................1");
                    Console.WriteLine("\n\nserverToken.token==>" + serverToken.token);
                    Console.WriteLine("\n\nserverToken.pk==>" + serverToken.pk);                   
                }
            },
            ex =>
            {
                MessageBox.Show("Exception = " + ex.Message);
            },
            () =>
            {
                Console.WriteLine("End of Process.. Releaseing all Resources used.");
            });
        }
    }`

1 个答案:

答案 0 :(得分:0)

以下是几个选项:

您可以使用HttpClient替换针对Web请求的更简单的async / await -model的Reactive Extensions模型(在WP7中还需要Microsoft.Bcl.Async)。使用HttpClient,您的代码最终会如下所示:

请求和回复:

        public static async Task<string> postAndGetResponse(String postData)
    {
        if (GlobalConstants.isGetToken)
        {
            //Pre Request for every reusest               
            await getServerTokenMethod();
        }

        var client = new HttpClient();
        var postMessage = new HttpRequestMessage(HttpMethod.Post, new Uri(Constants.SERVICE_URI));
        var postResult = await client.SendAsync(postMessage);

        var stringResult = await postResult.Content.ReadAsStringAsync();

        return stringResult;
    }

<强>视图模型:

    public class ListExampleViewModel
{
    SecurityToken sToken = null;
    public ListExampleViewModel()
    {
        GetData();
    }

    public async void GetData()
    {
        GlobalConstants.isGetToken = true;
        var listResults = await REQ_RESP.postAndGetResponse("postData");
    }
}

如果您想继续使用Reactive Extensions,另一个选择是查看RX的Concat方法。有了它,您可以链接令牌请求和实际的Web请求:https://stackoverflow.com/a/6754558/66988