HttpHelper类的调用方法详解
本文实例为大家分享了HttpHelper类的方法使用,供大家参考,具体内容如下
首先列出HttpHelper类
//////Http操作类 /// publicclassHttpHelper { privatestaticlog4net.ILogmLog=log4net.LogManager.GetLogger("HttpHelper"); [DllImport("wininet.dll",CharSet=CharSet.Auto,SetLastError=true)] publicstaticexternboolInternetSetCookie(stringlpszUrlName,stringlbszCookieName,stringlpszCookieData); [DllImport("wininet.dll",CharSet=CharSet.Auto,SetLastError=true)] publicstaticexternboolInternetGetCookie(stringlpszUrlName,stringlbszCookieName,StringBuilderlpszCookieData,refintlpdwSize); publicstaticStreamReadermLastResponseStream=null; publicstaticSystem.IO.StreamReaderLastResponseStream { get{returnmLastResponseStream;} } privatestaticCookieContainermCookie=null; publicstaticCookieContainerCookie { get{returnmCookie;} set{mCookie=value;} } privatestaticCookieContainermLastCookie=null; publicstaticHttpWebRequestCreateWebRequest(stringurl,HttpRequestTypehttpType,stringcontentType,stringdata,EncodingrequestEncoding,inttimeout,boolkeepAlive) { if(String.IsNullOrWhiteSpace(url)) { thrownewException("URL为空"); } HttpWebRequestwebRequest=null; StreamrequestStream=null; byte[]datas=null; switch(httpType) { caseHttpRequestType.GET: caseHttpRequestType.DELETE: if(!String.IsNullOrWhiteSpace(data)) { if(!url.Contains('?')) { url+="?"+data; } elseurl+="&"+data; } if(url.StartsWith("https:")) { System.Net.ServicePointManager.SecurityProtocol=SecurityProtocolType.Tls11|SecurityProtocolType.Tls12; ServicePointManager.ServerCertificateValidationCallback=newSystem.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); } webRequest=(HttpWebRequest)WebRequest.Create(url); webRequest.Method=Enum.GetName(typeof(HttpRequestType),httpType); if(contentType!=null) { webRequest.ContentType=contentType; } if(mCookie==null) { webRequest.CookieContainer=newCookieContainer(); } else { webRequest.CookieContainer=mCookie; } if(keepAlive) { webRequest.KeepAlive=keepAlive; webRequest.ReadWriteTimeout=timeout; webRequest.Timeout=60000; mLog.Info("请求超时时间..."+timeout); } break; default: if(url.StartsWith("https:")) { System.Net.ServicePointManager.SecurityProtocol=SecurityProtocolType.Tls11|SecurityProtocolType.Tls12; ServicePointManager.ServerCertificateValidationCallback=newSystem.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); } webRequest=(HttpWebRequest)WebRequest.Create(url); webRequest.Method=Enum.GetName(typeof(HttpRequestType),httpType); if(contentType!=null) { webRequest.ContentType=contentType; } if(mCookie==null) { webRequest.CookieContainer=newCookieContainer(); } else { webRequest.CookieContainer=mCookie; } if(keepAlive) { webRequest.KeepAlive=keepAlive; webRequest.ReadWriteTimeout=timeout; webRequest.Timeout=60000; mLog.Info("请求超时时间..."+timeout); } if(!String.IsNullOrWhiteSpace(data)) { datas=requestEncoding.GetBytes(data); } if(datas!=null) { webRequest.ContentLength=datas.Length; requestStream=webRequest.GetRequestStream(); requestStream.Write(datas,0,datas.Length); requestStream.Flush(); requestStream.Close(); } break; } //mLog.InfoFormat("请求Url:{0},HttpRequestType:{1},contentType:{2},data:{3}",url,Enum.GetName(typeof(HttpRequestType),httpType),contentType,data); returnwebRequest; } publicstaticCookieContainerGetLastCookie() { returnmLastCookie; } //////设置HTTP的Cookie,以后发送和请求用此Cookie /// ///CookieContainer publicstaticvoidSetHttpCookie(CookieContainercookie) { mCookie=cookie; } privatestaticHttpWebRequestmLastAsyncRequest=null; publicstaticHttpWebRequestLastAsyncRequest { get{returnmLastAsyncRequest;} set{mLastAsyncRequest=value;} } /// ///发送请求 /// ///请求Url /// 请求类型 /// contentType:application/x-www-form-urlencoded /// 请求数据 /// 请求数据传输时编码格式 /// 返回请求结果 publicstaticstringSendRequest(stringurl,HttpRequestTypehttpType,stringcontentType,stringdata,EncodingrequestEncoding,EncodingreponseEncoding,paramsAsyncCallback[]callBack) { inttimeout=0; boolkeepAlive=false; if(callBack!=null&&callBack.Length>0&&callBack[0]!=null) { keepAlive=true; timeout=1000*60*60; mLog.Info("写入读取超时时间..."+timeout); } //mLog.Info("开始创建请求...."); HttpWebRequestwebRequest=CreateWebRequest(url,httpType,contentType,data,requestEncoding,timeout,keepAlive); stringret=null; //mLog.Info("创建请求结束...."); if(callBack!=null&&callBack.Length>0&&callBack[0]!=null) { //mLog.Info("开始异步请求...."); mLastAsyncRequest=webRequest; webRequest.BeginGetResponse(callBack[0],webRequest); } else { //mLog.Info("开始同步请求...."); StreamReadersr=newStreamReader(webRequest.GetResponse().GetResponseStream(),reponseEncoding); ret=sr.ReadToEnd(); sr.Close(); } mLastCookie=webRequest.CookieContainer; //mLog.InfoFormat("结束请求Url:{0},HttpRequestType:{1},contentType:{2},结果:{3}",url,Enum.GetName(typeof(HttpRequestType),httpType),contentType,ret); returnret; } //////Http上传文件 /// publicstaticstringHttpUploadFile(stringurl,stringpath) { using(FileStreamfs=newFileStream(path,FileMode.Open,FileAccess.Read)) { //设置参数 HttpWebRequestrequest=WebRequest.Create(url)asHttpWebRequest; CookieContainercookieContainer=newCookieContainer(); request.CookieContainer=cookieContainer; request.AllowAutoRedirect=true; request.AllowWriteStreamBuffering=false; request.SendChunked=true; request.Method="POST"; request.Timeout=300000; stringboundary=DateTime.Now.Ticks.ToString("X");//随机分隔线 request.ContentType="multipart/form-data;charset=utf-8;boundary="+boundary; byte[]itemBoundaryBytes=Encoding.UTF8.GetBytes("\r\n--"+boundary+"\r\n"); byte[]endBoundaryBytes=Encoding.UTF8.GetBytes("\r\n--"+boundary+"--\r\n"); intpos=path.LastIndexOf("\\"); stringfileName=path.Substring(pos+1); //请求头部信息 StringBuildersbHeader=newStringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n",fileName)); byte[]postHeaderBytes=Encoding.UTF8.GetBytes(sbHeader.ToString()); request.ContentLength=itemBoundaryBytes.Length+postHeaderBytes.Length+fs.Length+endBoundaryBytes.Length; using(StreampostStream=request.GetRequestStream()) { postStream.Write(itemBoundaryBytes,0,itemBoundaryBytes.Length); postStream.Write(postHeaderBytes,0,postHeaderBytes.Length); intbytesRead=0; intarrayLeng=fs.Length<=4096?(int)fs.Length:4096; byte[]bArr=newbyte[arrayLeng]; intcounter=0; while((bytesRead=fs.Read(bArr,0,arrayLeng))!=0) { counter++; postStream.Write(bArr,0,bytesRead); } postStream.Write(endBoundaryBytes,0,endBoundaryBytes.Length); } //发送请求并获取相应回应数据 using(HttpWebResponseresponse=request.GetResponse()asHttpWebResponse) { //直到request.GetResponse()程序才开始向目标网页发送Post请求 using(Streaminstream=response.GetResponseStream()) { StreamReadersr=newStreamReader(instream,Encoding.UTF8); //返回结果网页(html)代码 stringcontent=sr.ReadToEnd(); returncontent; } } } } publicstaticstringHttpUploadFile(stringurl,MemoryStreamfiles,stringfileName) { using(MemoryStreamfs=files) { //设置参数 HttpWebRequestrequest=WebRequest.Create(url)asHttpWebRequest; CookieContainercookieContainer=newCookieContainer(); request.CookieContainer=cookieContainer; request.AllowAutoRedirect=true; request.AllowWriteStreamBuffering=false; request.SendChunked=true; request.Method="POST"; request.Timeout=300000; stringboundary=DateTime.Now.Ticks.ToString("X");//随机分隔线 request.ContentType="multipart/form-data;charset=utf-8;boundary="+boundary; byte[]itemBoundaryBytes=Encoding.UTF8.GetBytes("\r\n--"+boundary+"\r\n"); byte[]endBoundaryBytes=Encoding.UTF8.GetBytes("\r\n--"+boundary+"--\r\n"); //请求头部信息 StringBuildersbHeader=newStringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n",fileName)); byte[]postHeaderBytes=Encoding.UTF8.GetBytes(sbHeader.ToString()); request.ContentLength=itemBoundaryBytes.Length+postHeaderBytes.Length+fs.Length+endBoundaryBytes.Length; using(StreampostStream=request.GetRequestStream()) { postStream.Write(itemBoundaryBytes,0,itemBoundaryBytes.Length); postStream.Write(postHeaderBytes,0,postHeaderBytes.Length); intbytesRead=0; intarrayLeng=fs.Length<=4096?(int)fs.Length:4096; byte[]bArr=newbyte[arrayLeng]; intcounter=0; fs.Position=0; while((bytesRead=fs.Read(bArr,0,arrayLeng))!=0) { counter++; postStream.Write(bArr,0,bytesRead); } postStream.Write(endBoundaryBytes,0,endBoundaryBytes.Length); } //发送请求并获取相应回应数据 using(HttpWebResponseresponse=request.GetResponse()asHttpWebResponse) { //直到request.GetResponse()程序才开始向目标网页发送Post请求 using(Streaminstream=response.GetResponseStream()) { StreamReadersr=newStreamReader(instream,Encoding.UTF8); //返回结果网页(html)代码 stringcontent=sr.ReadToEnd(); returncontent; } } } } #regionpublicstatic方法 //////将请求的流转化为字符串 /// ////// publicstaticstringGetStr(Streaminfo) { stringresult=""; try { using(StreamReadersr=newStreamReader(info,System.Text.Encoding.UTF8)) { result=sr.ReadToEnd(); sr.Close(); } } catch { } returnresult; } /// ///参数转码 /// ////// publicstaticstringstringDecode(stringstr) { returnHttpUtility.UrlDecode(HttpUtility.UrlDecode(str,System.Text.Encoding.GetEncoding("UTF-8")),System.Text.Encoding.GetEncoding("UTF-8")); } /// ///json反序列化 /// ////// /// publicstaticTDeserialize (stringjson) { try { Tobj=Activator.CreateInstance (); using(MemoryStreamms=newMemoryStream(System.Text.Encoding.UTF8.GetBytes(json))) { DataContractJsonSerializerserializer=newDataContractJsonSerializer(obj.GetType()); return(T)serializer.ReadObject(ms); } } catch { returndefault(T); } } #endregion publicstaticboolCheckValidationResult(objectsender,X509Certificatecertificate,X509Chainchain,SslPolicyErrorssslPolicyErrors) {//总是接受 returntrue; } } publicenumHttpRequestType { POST, GET, DELETE, PUT, PATCH, HEAD, TRACE, OPTIONS }
然后列出HttpHelper的调用
1、不带参数调用
publicboolConnectServer() { try { stringurl="https://i.cnblogs.com"; stringxml=HttpHelper.SendRequest(url,HttpRequestType.POST,null,null,Encoding.UTF8,Encoding.UTF8); NormalResponsenr=HuaweiXMLHelper.GetNormalResponse(xml); if(nr.Code=="0") { HttpHelper.SetHttpCookie(HttpHelper.GetLastCookie()); mIsConnect=true; returntrue; } else { mIsConnect=false; returnfalse; } } catch(System.Exceptionex) { mIsConnect=false; returnfalse; } }
2.带参数调用
privateboolHandleIntelligentTask(stringtaskId,boolbStop) { try { if(!mIsConnect) { returnfalse; } StringBuildersb=newStringBuilder(); sb.AppendFormat("\r\n"); sb.AppendFormat(" \r\n"); stringxml=sb.ToString(); stringurl=mIAServerUrl+"/sdk_service/rest/video-analysis/handle-intelligent-analysis"; stringxml2=HttpHelper.SendRequest(url,HttpRequestType.POST,"text/plain;charset=utf-8",xml,Encoding.UTF8,Encoding.UTF8); NormalResponsenr=HuaweiXMLHelper.GetNormalResponse(xml2); if(nr.Code=="0") { returntrue; } else { returnfalse; } } catch(System.Exceptionex) { returnfalse; } }{0} \r\n",taskId);// sb.AppendFormat("{0} \r\n",bStop?0:1); sb.AppendFormat("
3.异步调用
privatevoidReStartAlarmServer(Listlist,stringalarmUrl,Thread[]listThread) { StopAlarm(alarmUrl,listThread); listThread[0]=newThread(newThreadStart(delegate() { try { if(!mIsConnect) { mLog.Error("未登录!--ReStartAlarmServer-结束!"); return; } mLog.Info("ReStartAlarmServer开始报警连接...."); if(String.IsNullOrWhiteSpace(alarmUrl))return; mLog.InfoFormat("ReStartAlarmServer请求报警:URL={0}",alarmUrl); stringxml="task-id=0"; stringxml2=HttpHelper.SendRequest(alarmUrl,HttpRequestType.POST,"application/x-www-form-urlencoded",xml,Encoding.UTF8,Encoding.UTF8,AlarmCallBack); mLog.Info("ReStartAlarmServer报警连接成功!"); } catch(System.Threading.ThreadAbortExceptionex) { mLog.Info("ReStartAlarmServer线程已人为终止!"+ex.Message,ex); } catch(System.Exceptionex) { mLog.Error("ReStartAlarmServer开始报警连接失败:"+ex.Message,ex); mLog.Info("ReStartAlarmServer开始重新报警连接...."); mTimes=50; } finally { } })); listThread[0].IsBackground=true; listThread[0].Start(); } privatevoidAlarmCallBack(IAsyncResultir) { try { HttpWebRequestwebRequest=(HttpWebRequest)ir.AsyncState; stringsalarmUrl=webRequest.Address.OriginalString; Thread[]alarmThead=dicAlarmUrls[salarmUrl]; HttpWebResponseresponse=(HttpWebResponse)webRequest.EndGetResponse(ir); Streamstream=response.GetResponseStream(); alarmThead[1]=newThread(newThreadStart(delegate() { try { byte[]buffer=newbyte[mAlarmReadCount]; intcount=0; stringstrMsg=""; intstartIndex=-1; intendIndex=-1; NormalResponseres=null; DateTimedtStart=DateTime.Now; DateTimedtEnd=DateTime.Now; while(!mIsCloseAlarm) { count=stream.Read(buffer,0,mAlarmReadCount); if(count>0) { strMsg+=Encoding.UTF8.GetString(buffer,0,count); startIndex=strMsg.IndexOf(" "); endIndex=strMsg.IndexOf(" "); stringxml=strMsg.Substring(startIndex,endIndex-startIndex+"".Length); res=HuaweiXMLHelper.GetNormalResponse(xml); strMsg=strMsg.Substring(endIndex+"".Length); startIndex=-1; endIndex=-1; break; } dtEnd=DateTime.Now; if((dtEnd-dtStart).TotalSeconds>10) { thrownewException("连接信息未有获取到,需要重启报警!"); } } while(!mIsCloseAlarm) { count=stream.Read(buffer,0,mAlarmReadCount); if(count>0) { stringtemp=Encoding.UTF8.GetString(buffer,0,count); strMsg+=temp; while(strMsg.Length>0) { if(startIndex==-1)//未发现第一个{ startIndex=strMsg.IndexOf(" "); if(startIndex==-1) { if(strMsg.Length>=" ".Length) { strMsg=strMsg.Substring(strMsg.Length-" ".Length); } break; } } if(startIndex>=0) { inti=startIndex+" ".Length; inti1=strMsg.IndexOf("",i);//找到轨迹节点结束 inti2=strMsg.IndexOf("",i);//找到报警节点结束,发现一条报警 if(i1==-1&&i2==-1)//没有标志结束 { break; } elseif(i1>=0&&(i1".Length; inttaskInfoEndIndex=strMsg.IndexOf(" ",i); if(taskInfoEndIndex>0)//必须有任务结束节点 { i=taskInfoEndIndex+"".Length); startIndex=-1; endIndex=-1; continue; } elseif(i2>0&&(i2 ".Length)+""; Threadth=newThread(newThreadStart(delegate() { ParseAlarmXml(alarmXml); })); th.IsBackground=true; th.Start(); strMsg=strMsg.Substring(endIndex+"".Length); startIndex=-1; endIndex=-1; continue; } } else { break; } } } } else { Console.WriteLine("##########读取报警反馈:无"); Thread.Sleep(1000); } } } catch(System.Threading.ThreadAbortExceptionex) { mLog.Info("AlarmCallBack...7"); try { if(stream!=null) { stream.Close(); stream.Dispose(); response.Close(); } } catch { } mLog.Info("AlarmCallBack线程已人为终止!--0"+ex.Message,ex); } catch(IOExceptionex) { mLog.Info("AlarmCallBack...8"); try { if(stream!=null) { stream.Close(); stream.Dispose(); response.Close(); } } catch { } } catch(ObjectDisposedExceptionex) { mLog.Info("AlarmCallBack...9"); mLog.Info("AlarmCallBack读取流已人为终止!--2"+ex.Message,ex); try { if(stream!=null) { stream.Close(); stream.Dispose(); response.Close(); } } catch { } } catch(System.Exceptionex) { mLog.Info("AlarmCallBack...10"); mLog.Error("AlarmCallBack0:"+ex.Message,ex); try { if(stream!=null) { stream.Close(); stream.Dispose(); response.Close(); } } catch { } } finally { } })); alarmThead[1].IsBackground=true; alarmThead[1].Start(); } catch(System.Exceptionex) { mLog.Info("AlarmCallBack...11"); mLog.Error("AlarmCallBack1:"+ex.Message,ex); mLog.Info("AlarmCallBack开始重新报警连接....3"); mTimes=50; } finally { } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。