httpwebrequest 用GET方法请求时报无法发送具有此谓词类型的内容正文

执行下面一段代码时,捕捉到异常:ProtocolViolationException

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "get";
            byte[] requestBytes = System.Text.Encoding.UTF8.GetBytes(data);
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = requestBytes.Length;
            request.Timeout = 6000;
            try
            {
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(requestBytes, 0, requestBytes.Length);
                requestStream.Close();

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);
                ret = reader.ReadToEnd();
            }
            catch (Exception)
            {
                return "Put data error";
            }

原因是以流的方式提交数据的时候不能使用get方法,必须用post方法,改为下面的写法即可。

request.Method = "get";

 

posted on 2012-12-14 17:57  jenqz  阅读(5718)  评论(1编辑  收藏  举报