Why do I get ProtocolViolationException when I do BeginGetRequestStream

谁都会走 提交于 2019-12-31 02:41:18

问题


I am new to silverlight. I am programming in Visual Studio 2010 for Windows phone. I try to do HttpWebRequest but debugger says ProtocolViolationException. This my code

 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);
            }

        }

回答1:


I think the problem is that you aren't using POST, but GET. Try this:

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



回答2:


You aren't even doing anything with the request stream when you get it.

HttpWebRequest is assuming that the reason you tried to get it, was to write content to it (the only reason for getting it, after all).

Since you aren't allowed to include content in a GET request, it realises that the only thing you can do with that stream, is something that would violate the HTTP protocol. As a tool for using the HTTP protocol, it's its job to stop you making that mistake.

So it throws ProtocolViolationException.

Cut out the bit about the request stream - it's only for POST and PUT. Go straight to GetResponse() or BeginGetResponse() at that point.



来源:https://stackoverflow.com/questions/11955391/why-do-i-get-protocolviolationexception-when-i-do-begingetrequeststream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!