2

我是银光新手。我正在为 Windows 手机使用 Visual Studio 2010 编程。我尝试做 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);
            }

        }
4

2 回答 2

5

我认为问题在于您使用的不是 POST,而是 GET。尝试这个:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(auth);
request.Method = "POST";
request.BeginGetRequestStream(RequestCallBack, request);
于 2012-08-14T15:16:35.410 回答
1

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

HttpWebRequest假设您尝试获取它的原因是向其写入内容(毕竟,获取它的唯一原因)。

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

所以它抛出ProtocolViolationException

删掉有关请求流的部分 - 它仅适用于 POST 和 PUT。直接到那个点GetResponse()BeginGetResponse()那个点。

于 2012-08-14T16:46:07.913 回答