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";