HttpWebRequest问题 [英] Problem with HttpWebRequest

查看:73
本文介绍了HttpWebRequest问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨!

我正在Windows 8,Phone 7和Phone 8的PCL上工作.我编写了以下代码,以通过POST发出HttpWebRequest并从服务器获取响应:

Im working on a PCL for Windows 8, Phone 7 and Phone 8. I have written this code to make a HttpWebRequest with a POST and to get a response from the server:

 request = (HttpWebRequest)WebRequest.Create(BaseUrl + @"myserver/mymethod");
            request.Method = "POST";
            request.ContentType = "message/rfc822";          
            request.BeginGetRequestStream(new AsyncCallback(GetRequestCallBack), postData);
            mySync.WaitOne();  

处理请求/响应的方法如下:

The methods that handle the request/response looks like this:

 private void GetRequestCallBack(IAsyncResult aResult)
        {

            using (StreamWriter streamWriter = new StreamWriter(request.EndGetRequestStream(aResult)))
            {
                string json = aResult.AsyncState.ToString();               
                streamWriter.Write(json);
                streamWriter.Flush();               
            }

            request.BeginGetResponse(new AsyncCallback(GetResponseCallBack), request);
           
        }

        private void GetResponseCallBack(IAsyncResult aResult)
        {
           using (var streamReader = new StreamReader(request.EndGetResponse(aResult).GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();                
                mySync.Set();
            }
        }

在Phone 8模拟器上运行此代码时,我遇到的问题是代码在mySync.WaitOne()上暂停.这段代码来自我在标准Windows窗体应用程序上进行的测试,并且需要waitone,因为还有其他方法必须等待 在此网络请求完成之前.

The problem I have when running this code on the Phone 8 emulator is that the code halts on mySync.WaitOne(). This code is from a test I made on a standard windows forms application, and the waitone is needed because there are other methods that must wait before this web request is finished.

显然,这在Phone 8中不起作用,因为它似乎在UI线程上运行了异步方法.我该如何解决?

Obviously this won't work in Phone 8 because it seems it run the async methods on the UI thread. How can I solve this?

/亨里克

Henrik

推荐答案

页面底部此链接处有一个示例.也许可以帮上忙.

There is a sample at the bottom of the page at this link. Maybe it can help.

http://msdn.microsoft.com/zh-CN/library/windowsphone/develop/8y7x3zz2%28v=vs.105%29.aspx


这篇关于HttpWebRequest问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆