2024年1月25日发(作者:)

//body是要传递的参数,格式"roleId=1&uid=2"//post的cotentType填写://"application/x-www-form-urlencoded"//soap填写:"text/xml;charset=utf-8"publicstaticstringPostHttp(stringurl,stringbody,stringcontentType){HttpWebRequesthttpWebRequest=(HttpWebRequest)(url);tType=contentType;="POST";t=20000;byte[]btBodys=es(body);tLength=;uestStream().Write(btBodys,0,);HttpWebResponsehttpWebResponse(HttpWebResponse)ponse();StreamReaderstreamReaderStreamReader(ponseStream());stringresponseContent=End();();();();();returnresponseContent;}POST方法(httpWebRequest)///

///通过WebClient类Post数据到远程地址,需要Basic认证;///调用端自己处理异常/////////name=张三&age=20///请先确认目标网页的编码方式/////////publicstaticstringRequest_WebClient(stringuri,stringparamStr,Encodingencoding,stringusername,stringpassword)==new

{if(encoding==null)encoding=8;stringresult=;WebClientwc=newWebClient();//采取POST方式必须加的("Content-Type","application/x-www-form-urlencoded");byte[]postData=es(paramStr);if(!OrEmpty(username)&&!OrEmpty(password)){tials=GetCredentialCache(uri,username,password);("Authorization",GetAuthorization(username,password));}byte[]responseData=Data(uri,"POST",postData);//得到返回字符流ing(responseData);//解码}POST方法(WebClient)publicstaticstringGetHttp(stringurl,HttpContexthttpContext){stringqueryString="?";foreach(s){queryString+=key+"="+tring[key]+"&";}queryString=ing(0,-1);HttpWebRequestqueryString);httpWebRequest=(HttpWebRequest)(url+tType="application/json";="GET";t=20000;//byte[]btBodys=es(body);

//tLength=;//uestStream().Write(btBodys,0,);HttpWebResponsehttpWebResponse(HttpWebResponse)ponse();StreamReaderstreamReaderStreamReader(ponseStream());stringresponseContent=End();();();returnresponseContent;}Get方法(HttpWebRequest)///

///通过WebRequest/WebResponse类访问远程地址并返回结果,需要Basic认证;///调用端自己处理异常/////////访问超时时间,单位毫秒;如果不设置超时时间,传入0///如果不知道具体的编码,传入null/////////publicstaticstringRequest_WebRequest(stringuri,inttimeout,Encodingencoding,stringusername,stringpassword){stringresult=;WebRequestrequest=(newUri(uri));if(!OrEmpty(username)&&!OrEmpty(password)){tials=GetCredentialCache(uri,username,password);("Authorization",GetAuthorization(username,password));}if(timeout>0)t=timeout;==new

WebResponseresponse=ponse();Streamstream=ponseStream();StreamReadersr=encoding==null?newStreamReader(stream):newStreamReader(stream,encoding);result=End();();();returnresult;}#region#生成HttpBasic访问凭证#privatestaticCredentialCacheGetCredentialCache(stringuri,stringusername,stringpassword){stringauthorization=("{0}:{1}",username,password);CredentialCachecredCache=newCredentialCache();(newUri(uri),"Basic",newNetworkCredential(username,password));returncredCache;}privatestaticstringGetAuthorization(stringusername,stringpassword){stringauthorization=("{0}:{1}",username,password);return"BasicASCIIEncoding().GetBytes(authorization));}#endregionbasic验证的WebRequest/WebResponse"+64String(new