【问题标题】:Why do I get ProtocolViolationException when I do BeginGetRequestStream为什么我在执行 BeginGetRequestStream 时会收到 ProtocolViolationException
【发布时间】:2012-08-14 15:10:31
【问题描述】:

我是 Silverlight 的新手。我正在使用 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);
            }

        }

【问题讨论】:

  • 您忘记清理一个客户端密钥/ID 对
  • 有人可以给我 HttpWebRequest 的工作代码吗?

标签: c# silverlight windows-phone


【解决方案1】:

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

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

【讨论】:

  • @user1597524 那么你不能在流中写任何东西。在 GET 请求中包含内容违反了 HTTP 协议。这是违反协议的。我不知道 WebRequest 会立即抛出该异常(而不是让您在之后和获得响应之前将“POST”、“PUT”等设置为方法),但我当然希望在某个时候出现 ProtocolViolationException .
【解决方案2】:

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

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

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

所以它抛出ProtocolViolationException

删掉有关请求流的部分内容 - 它仅适用于 POST 和 PUT。到时候直接去GetResponse()BeginGetResponse()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    • 2012-05-31
    • 2015-12-13
    • 2020-10-17
    • 2010-09-15
    相关资源
    最近更新 更多