HttpWebRequest请求时无法发送具有此谓词类型的内容正文。

时间:2016-10-30 07:28:48   收藏:0   阅读:4397
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl); //--需要封装的参数 
            request.CookieContainer = new CookieContainer();
            CookieContainer cookie = request.CookieContainer;//如果用不到Cookie,删去即可  
            //以下是发送的http头 
            request.Referer = "";
            request.Accept = "Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            request.Headers["Accept-Language"] = "zh-CN,zh;q=0.";
            request.Headers["Accept-Charset"] = "GBK,utf-8;q=0.7,*;q=0.3";
            request.UserAgent = "User-Agent:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1";
            request.KeepAlive = true;
            //上面的http头看情况而定,但是下面俩必须加  
            request.ContentType = "application/x-www-form-urlencoded";
            Encoding encoding = Encoding.UTF8;//根据网站的编码自定义
            request.Method ="get";  //--需要将get改为post才可行
            string postDataStr;
            Stream requestStream = request.GetRequestStream();
            if (postDatas != "")
            {
                postDataStr=postDatas;//--需要封装,形式如“arg=arg1&arg2=arg2” 
                byte[] postData = encoding.GetBytes(postDataStr);//postDataStr即为发送的数据,
                request.ContentLength = postData.Length;
                requestStream.Write(postData, 0, postData.Length);
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();


            StreamReader streamReader = new StreamReader(responseStream, encoding);
            string retString = streamReader.ReadToEnd();

            streamReader.Close();
            responseStream.Close();
            return retString;

  如果是以流的方式提交表单数据的时候不能使用get方法,必须用post方法,

 

改为

request.Method ="post";  就可以了。  做一个记号

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!