当我执行BeginGetRequestStream时,为什么会出现ProtocolViolationException

时间:2012-08-14 15:10:32

标签: c# silverlight windows-phone

我是银光的新手。我正在使用Visual Studio 2010 for Windows phone进行编程。 我尝试做HttpWebRequest,但调试器说ProtocolViolationException。 这是我的代码

 private void log_Click(object sender, RoutedEventArgs e)
        {
            //auth thi is my url for request
            string auth;
            string login = Uri.EscapeUriString(this.login.Text);
            string password = Uri.EscapeUriString(this.pass.Password);
            auth = "https://api.vk.com/oauth/token";
            auth += "?grant_type=password" + "&client_id=*****&client_secret=******&username=" + login + "&password=" + password + "&scope=notify,friends,messages";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(auth);
            request.BeginGetRequestStream(RequestCallBack, request);//on this line debager say ProtocolViolationExceptio
        }

        void RequestCallBack(IAsyncResult result)
        {
            HttpWebRequest request = result.AsyncState as HttpWebRequest;
            Stream stream = request.EndGetRequestStream(result);
            request.BeginGetResponse(ResponceCallBack, request);
        }
        void ResponceCallBack(IAsyncResult result)
        {
            HttpWebRequest request = result.AsyncState as HttpWebRequest;
            HttpWebResponse response = request.EndGetResponse(result) as HttpWebResponse;
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                string a =sr.ReadToEnd();
                MessageBox.Show(a);
            }

        }

2 个答案:

答案 0 :(得分:5)

我认为问题在于你没有使用POST,而是GET。试试这个:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(auth);
request.Method = "POST";
request.BeginGetRequestStream(RequestCallBack, request);

答案 1 :(得分:0)

当你得到它时,你甚至没有对请求流做任何事情。

HttpWebRequest假设你试图获得它的原因是为它写内容(毕竟是获得它的唯一原因)。

由于您不允许在GET请求中包含内容,因此它意识到您可以对该流执行的唯一操作是违反HTTP协议。作为使用HTTP协议的工具,它的作用是阻止你犯这个错误。

所以它会抛出ProtocolViolationException

删除有关请求流的位 - 它仅用于POST和PUT。此时直接转到GetResponse()BeginGetResponse()