欢迎来到天天文库
浏览记录
ID:37914562
大小:36.00 KB
页数:4页
时间:2019-06-02
《C#通过WebClient,HttpWebRequest实现http的post和get方法》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、//body是要传递的参数,格式"roleId=1&uid=2"//post的cotentType填写://"application/x-www-form-urlencoded"//soap填写:"text/xml;charset=utf-8"publicstaticstringPostHttp(stringurl,stringbody,stringcontentType){HttpWebRequesthttpWebRequest=(HttpWebRequest)WebRequest.Create(ur
2、l);httpWebRequest.ContentType=contentType;httpWebRequest.Method="POST";httpWebRequest.Timeout=20000;byte[]btBodys=Encoding.UTF8.GetBytes(body);httpWebRequest.ContentLength=btBodys.Length;httpWebRequest.GetRequestStream().Write(btBodys,0,btBodys.Length);H
3、ttpWebResponsehttpWebResponse=(HttpWebResponse)httpWebRequest.GetResponse();StreamReaderstreamReader=newStreamReader(httpWebResponse.GetResponseStream());stringresponseContent=streamReader.ReadToEnd();httpWebResponse.Close();streamReader.Close();httpWebR
4、equest.Abort();httpWebResponse.Close();returnresponseContent;}POST方法(httpWebRequest)//////通过WebClient类Post数据到远程地址,需要Basic认证;///调用端自己处理异常/////////name=张三&age=20///5、ng">请先确认目标网页的编码方式/////////publicstaticstringRequest_WebClient(stringuri,stringparamStr,Encodingencoding,stringusername,stringpassword){if(encoding==null)encoding=Encod6、ing.UTF8;stringresult=string.Empty;WebClientwc=newWebClient();//采取POST方式必须加的Headerwc.Headers.Add("Content-Type","application/x-www-form-urlencoded");byte[]postData=encoding.GetBytes(paramStr);if(!string.IsNullOrEmpty(username)&&!string.IsNullOrEmpty(pass7、word)){wc.Credentials=GetCredentialCache(uri,username,password);wc.Headers.Add("Authorization",GetAuthorization(username,password));}byte[]responseData=wc.UploadData(uri,"POST",postData);//得到返回字符流returnencoding.GetString(responseData);//解码}POST方法(WebClie8、nt)publicstaticstringGetHttp(stringurl,HttpContexthttpContext){stringqueryString="?";foreach(stringkeyinhttpContext.Request.QueryString.AllKeys){queryString+=key+"="+httpContext.Request.QueryString[key]+"&";}queryString=qu
5、ng">请先确认目标网页的编码方式/////////publicstaticstringRequest_WebClient(stringuri,stringparamStr,Encodingencoding,stringusername,stringpassword){if(encoding==null)encoding=Encod
6、ing.UTF8;stringresult=string.Empty;WebClientwc=newWebClient();//采取POST方式必须加的Headerwc.Headers.Add("Content-Type","application/x-www-form-urlencoded");byte[]postData=encoding.GetBytes(paramStr);if(!string.IsNullOrEmpty(username)&&!string.IsNullOrEmpty(pass
7、word)){wc.Credentials=GetCredentialCache(uri,username,password);wc.Headers.Add("Authorization",GetAuthorization(username,password));}byte[]responseData=wc.UploadData(uri,"POST",postData);//得到返回字符流returnencoding.GetString(responseData);//解码}POST方法(WebClie
8、nt)publicstaticstringGetHttp(stringurl,HttpContexthttpContext){stringqueryString="?";foreach(stringkeyinhttpContext.Request.QueryString.AllKeys){queryString+=key+"="+httpContext.Request.QueryString[key]+"&";}queryString=qu
此文档下载收益归作者所有