当前位置: 移动技术网 > IT编程>开发语言>c# > HttpHelper类的调用方法详解

HttpHelper类的调用方法详解

2019年07月18日  | 移动技术网IT编程  | 我要评论

本文实例为大家分享了httphelper类的方法使用,供大家参考,具体内容如下

首先列出httphelper类

/// <summary>
 /// http操作类
 /// </summary>
 public class httphelper
 {
  private static log4net.ilog mlog = log4net.logmanager.getlogger("httphelper");

  [dllimport("wininet.dll", charset = charset.auto, setlasterror = true)]
  public static extern bool internetsetcookie(string lpszurlname, string lbszcookiename, string lpszcookiedata);

  [dllimport("wininet.dll", charset = charset.auto, setlasterror = true)]
  public static extern bool internetgetcookie(string lpszurlname, string lbszcookiename, stringbuilder lpszcookiedata, ref int lpdwsize);
  public static streamreader mlastresponsestream = null;
  public static system.io.streamreader lastresponsestream
  {
   get { return mlastresponsestream; }
  }
  private static cookiecontainer mcookie = null;
  public static cookiecontainer cookie
  {
   get { return mcookie; }
   set { mcookie = value; }
  }
  private static cookiecontainer mlastcookie = null;
  public static httpwebrequest createwebrequest(string url, httprequesttype httptype, string contenttype, string data, encoding requestencoding, int timeout, bool keepalive)
  {
   if (string.isnullorwhitespace(url))
   {
    throw new exception("url为空");
   }
   httpwebrequest webrequest = null;
   stream requeststream = null;
   byte[] datas = null;
   switch (httptype)
   {
    case httprequesttype.get:
    case httprequesttype.delete:
     if (!string.isnullorwhitespace(data))
     {
      if (!url.contains('?'))
      {
       url += "?" + data;
      }
      else url += "&" + data;
     }
     if(url.startswith("https:"))
     {
      system.net.servicepointmanager.securityprotocol = securityprotocoltype.tls11 | securityprotocoltype.tls12;
      servicepointmanager.servercertificatevalidationcallback = new system.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 = new cookiecontainer();
     }
     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 = new system.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 = new cookiecontainer();
     }
     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);
   return webrequest;
  }
  public static cookiecontainer getlastcookie()
  {
   return mlastcookie;
  }
  /// <summary>
  /// 设置http的cookie,以后发送和请求用此cookie
  /// </summary>
  /// <param name="cookie">cookiecontainer</param>
  public static void sethttpcookie(cookiecontainer cookie)
  {
   mcookie = cookie;
  }
  private static httpwebrequest mlastasyncrequest = null;
  public static httpwebrequest lastasyncrequest
  {
   get { return mlastasyncrequest; }
   set { mlastasyncrequest = value; }
  }
  /// <summary>
  /// 发送请求
  /// </summary>
  /// <param name="url">请求url</param>
  /// <param name="httptype">请求类型</param>
  /// <param name="contenttype">contenttype:application/x-www-form-urlencoded</param>
  /// <param name="data">请求数据</param>
  /// <param name="encoding">请求数据传输时编码格式</param>
  /// <returns>返回请求结果</returns>
  public static string sendrequest(string url, httprequesttype httptype, string contenttype, string data, encoding requestencoding, encoding reponseencoding, params asynccallback[] callback)
  {

   int timeout = 0;
   bool keepalive = false;
   if (callback != null && callback.length > 0 && callback[0] != null)
   {
    keepalive = true;
    timeout = 1000*60*60;
    mlog.info("写入读取超时时间..." + timeout);
   }
   // mlog.info("开始创建请求....");
   httpwebrequest webrequest = createwebrequest(url, httptype, contenttype, data, requestencoding,timeout,keepalive);
   string ret = null;
   // mlog.info("创建请求结束....");
   if (callback != null && callback.length > 0 && callback[0] != null)
   {
    // mlog.info("开始异步请求....");
    mlastasyncrequest = webrequest;
    webrequest.begingetresponse(callback[0], webrequest);
   }
   else
   {
    // mlog.info("开始同步请求....");
    streamreader sr = new streamreader(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);
   return ret;
  }

  /// <summary>
  /// http上传文件
  /// </summary>
  public static string httpuploadfile(string url, string path)
  {
   using (filestream fs = new filestream(path, filemode.open, fileaccess.read))
   {
    // 设置参数
    httpwebrequest request = webrequest.create(url) as httpwebrequest;
    cookiecontainer cookiecontainer = new cookiecontainer();
    request.cookiecontainer = cookiecontainer;
    request.allowautoredirect = true;
    request.allowwritestreambuffering = false;
    request.sendchunked = true;
    request.method = "post";
    request.timeout = 300000;

    string boundary = 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");
    int pos = path.lastindexof("\\");
    string filename = path.substring(pos + 1);

    //请求头部信息
    stringbuilder sbheader = new stringbuilder(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 (stream poststream = request.getrequeststream())
    {
     poststream.write(itemboundarybytes, 0, itemboundarybytes.length);
     poststream.write(postheaderbytes, 0, postheaderbytes.length);
     int bytesread = 0;

     int arrayleng = fs.length <= 4096 ? (int)fs.length : 4096;
     byte[] barr = new byte[arrayleng];
     int counter = 0;
     while ((bytesread = fs.read(barr, 0, arrayleng)) != 0)
     {
      counter++;
      poststream.write(barr, 0, bytesread);
     }
     poststream.write(endboundarybytes, 0, endboundarybytes.length);
    }

    //发送请求并获取相应回应数据
    using (httpwebresponse response = request.getresponse() as httpwebresponse)
    {
     //直到request.getresponse()程序才开始向目标网页发送post请求
     using (stream instream = response.getresponsestream())
     {
      streamreader sr = new streamreader(instream, encoding.utf8);
      //返回结果网页(html)代码
      string content = sr.readtoend();
      return content;
     }
    }
   }
  }

  public static string httpuploadfile(string url, memorystream files, string filename)
  {
   using (memorystream fs = files)
   {
    // 设置参数
    httpwebrequest request = webrequest.create(url) as httpwebrequest;
    cookiecontainer cookiecontainer = new cookiecontainer();
    request.cookiecontainer = cookiecontainer;
    request.allowautoredirect = true;
    request.allowwritestreambuffering = false;
    request.sendchunked = true;
    request.method = "post";
    request.timeout = 300000;

    string boundary = 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");

    //请求头部信息
    stringbuilder sbheader = new stringbuilder(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 (stream poststream = request.getrequeststream())
    {
     poststream.write(itemboundarybytes, 0, itemboundarybytes.length);
     poststream.write(postheaderbytes, 0, postheaderbytes.length);
     int bytesread = 0;

     int arrayleng = fs.length <= 4096 ? (int)fs.length : 4096;
     byte[] barr = new byte[arrayleng];
     int counter = 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 (httpwebresponse response = request.getresponse() as httpwebresponse)
    {
     //直到request.getresponse()程序才开始向目标网页发送post请求
     using (stream instream = response.getresponsestream())
     {
      streamreader sr = new streamreader(instream, encoding.utf8);
      //返回结果网页(html)代码
      string content = sr.readtoend();
      return content;
     }
    }
   }
  }

  #region public static 方法

  /// <summary>
  /// 将请求的流转化为字符串
  /// </summary>
  /// <param name="info"></param>
  /// <returns></returns>
  public static string getstr(stream info)
  {
   string result = "";
   try
   {
    using (streamreader sr = new streamreader(info, system.text.encoding.utf8))
    {
     result = sr.readtoend();
     sr.close();
    }
   }
   catch
   {
   }
   return result;
  }

  /// <summary>
  /// 参数转码
  /// </summary>
  /// <param name="str"></param>
  /// <returns></returns>
  public static string stringdecode(string str)
  {
   return httputility.urldecode(httputility.urldecode(str, system.text.encoding.getencoding("utf-8")), system.text.encoding.getencoding("utf-8"));
  }

  /// <summary>
  /// json反序列化
  /// </summary>
  /// <typeparam name="t"></typeparam>
  /// <param name="json"></param>
  /// <returns></returns>
  public static t deserialize<t>(string json)
  {
   try
   {
    t obj = activator.createinstance<t>();
    using (memorystream ms = new memorystream(system.text.encoding.utf8.getbytes(json)))
    {
     datacontractjsonserializer serializer = new datacontractjsonserializer(obj.gettype());
     return (t)serializer.readobject(ms);
    }
   }
   catch
   {
    return default(t);
   }
  }

  #endregion

  public static bool checkvalidationresult(object sender, x509certificate certificate, x509chain chain, sslpolicyerrors sslpolicyerrors)
  { // 总是接受 
   return true;
  }
 
 }
 public enum httprequesttype
 {
  post,
  get,
  delete,
  put,
  patch,
  head,
  trace,
  options
 }

然后列出httphelper的调用

1、不带参数调用

public bool connectserver()
    {
      try
      {
        string url = "https://i.cnblogs.com";

        string xml = httphelper.sendrequest(url, httprequesttype.post, null, null, encoding.utf8, encoding.utf8);
        normalresponse nr = huaweixmlhelper.getnormalresponse(xml);
        if (nr.code == "0")
        {
httphelper.sethttpcookie(httphelper.getlastcookie());
          misconnect = true;
          return true;
        }
        else
        {
          misconnect = false;
          return false;
        }
      }
      catch (system.exception ex)
      {
        misconnect = false;
        return false;
      }
    }


2.带参数调用

private bool handleintelligenttask(string taskid,bool bstop)
    {
      try
      {
        if (!misconnect)
        {
          return false;
        }
        stringbuilder sb = new stringbuilder();
        sb.appendformat("<request>\r\n");
        sb.appendformat("<task_id>{0}</task_id>\r\n", taskid);//<!-- task-id为调用方生成的uuid或其它串 -->
        sb.appendformat("<status>{0}</status>\r\n",bstop?0:1);
        sb.appendformat("</request>\r\n");
        string xml = sb.tostring();
        string url = miaserverurl + "/sdk_service/rest/video-analysis/handle-intelligent-analysis";
        string xml2 = httphelper.sendrequest(url, httprequesttype.post, "text/plain;charset=utf-8", xml, encoding.utf8, encoding.utf8);
        normalresponse nr = huaweixmlhelper.getnormalresponse(xml2);
        if (nr.code == "0")
        {
          return true;
        }
        else
        {
          return false;
        }
      }
      catch (system.exception ex)
      {
        return false;
      }

    }

3.异步调用

private void restartalarmserver(list<string> list, string alarmurl, thread[] listthread)
    {
      stopalarm(alarmurl, listthread);
      listthread[0]= new thread(new threadstart(delegate()
            {
              try
              {
                if (!misconnect)
                {
                  mlog.error("未登录!--restartalarmserver-结束!");
                  return;
                }
                mlog.info("restartalarmserver开始报警连接....");
                if (string.isnullorwhitespace(alarmurl)) return;
                mlog.infoformat("restartalarmserver请求报警:url={0}", alarmurl);
                string xml = "task-id=0";
                string xml2 = httphelper.sendrequest(alarmurl, httprequesttype.post, "application/x-www-form-urlencoded", xml, encoding.utf8, encoding.utf8, alarmcallback);
                mlog.info("restartalarmserver报警连接成功!");
              }
              catch (system.threading.threadabortexception ex)
              {
                mlog.info("restartalarmserver线程已人为终止!" + ex.message, ex);
              }
              catch (system.exception ex)
              {
                mlog.error("restartalarmserver开始报警连接失败:" + ex.message, ex);
                mlog.info("restartalarmserver开始重新报警连接....");
                mtimes = 50;
              }
              finally
              {
                
              }
            }));
      listthread[0].isbackground = true;
      listthread[0].start();
    }
    private void alarmcallback(iasyncresult ir)
    {
      try
      {
        httpwebrequest webrequest = (httpwebrequest)ir.asyncstate;
        string salarmurl = webrequest.address.originalstring;
        thread[] alarmthead = dicalarmurls[salarmurl];
        httpwebresponse response = (httpwebresponse)webrequest.endgetresponse(ir);
        stream stream = response.getresponsestream();
        alarmthead[1]= new thread(new threadstart(delegate()
        {
          try
          {
            byte[] buffer = new byte[malarmreadcount];
            int count = 0;
            string strmsg = "";
            int startindex = -1;
            int endindex = -1;

            normalresponse res = null;
            datetime dtstart = datetime.now;
            datetime dtend = datetime.now;
            while (!misclosealarm)
            {
              count = stream.read(buffer, 0, malarmreadcount);
              if (count > 0)
              {
                strmsg += encoding.utf8.getstring(buffer, 0, count);
                startindex = strmsg.indexof("<response>");
                endindex = strmsg.indexof("</response>");
                string xml = strmsg.substring(startindex, endindex - startindex + "</response>".length);
                res = huaweixmlhelper.getnormalresponse(xml);
                strmsg = strmsg.substring(endindex + "</response>".length);
                startindex = -1;
                endindex = -1;
                break;
              }
              dtend = datetime.now;
              if ((dtend - dtstart).totalseconds > 10)
              {
                throw new exception("连接信息未有获取到,需要重启报警!");
              }
            }
            while (!misclosealarm)
            {
              count = stream.read(buffer, 0, malarmreadcount);
              if (count > 0)
              {
                string temp = encoding.utf8.getstring(buffer, 0, count);
                strmsg += temp;
                while (strmsg.length > 0)
                {
                  if (startindex == -1)//未发现第一个<task-info>
                  {
                    startindex = strmsg.indexof("<task-info>");
                    if (startindex == -1)
                    {
                      if (strmsg.length >= "<task-info>".length)
                      {
                        strmsg = strmsg.substring(strmsg.length - "<task-info>".length);
                      }
                      break;
                    }
                  }
                  if (startindex >= 0)
                  {
                    int i = startindex + "<task-info>".length;
                    int taskinfoendindex = strmsg.indexof("</task-info>", i);
                    if (taskinfoendindex > 0)//必须有任务结束节点
                    {
                      i = taskinfoendindex + "</task-info>".length;
                      int i1 = strmsg.indexof("</attach-rules>", i);//找到轨迹节点结束
                      int i2 = strmsg.indexof("</alarm>", i);//找到报警节点结束,发现一条报警
                      if (i1 == -1 && i2 == -1)//没有标志结束
                      {
                        break;
                      }
                      else if (i1 >= 0 && (i1 < i2 || i2 == -1))//找到轨迹结束节点
                      {
                        strmsg = strmsg.substring(i1 + "</attach-rules>".length);
                        startindex = -1;
                        endindex = -1;
                        continue;
                      }
                      else if (i2 > 0 && (i2 < i1 || i1 == -1))//找报警节点
                      {
                        endindex = i2;//找到报警节点结束,发现一条报警
                        string alarmxml = "<taskalarm>" + strmsg.substring(startindex, endindex - startindex + "</alarm>".length) + "</taskalarm>";

                        thread th = new thread(new threadstart(delegate()
                        {
                          parsealarmxml(alarmxml);
                        }));
                        th.isbackground = true;
                        th.start();

                        strmsg = strmsg.substring(endindex + "</alarm>".length);
                        startindex = -1;
                        endindex = -1;
                        continue;
                      }
                    }
                    else
                    {
                      break;
                    }
                  }
                }
              }
              else
              {
                console.writeline("##########读取报警反馈:无");
                thread.sleep(1000);
              }
            }
          }
          catch (system.threading.threadabortexception ex)
          {
            mlog.info("alarmcallback...7");
            try
            {
              if (stream != null)
              {
                stream.close();
                stream.dispose();
                response.close();
              }
            }
            catch
            {
            }
            mlog.info("alarmcallback线程已人为终止!--0" + ex.message, ex);
          }
          catch(ioexception ex)
          {
            mlog.info("alarmcallback...8");
            try
            {
              if (stream != null)
              {
                stream.close();
                stream.dispose();
                response.close();
              }
            }
            catch
            {
            }
          }
          catch (objectdisposedexception ex)
          {
            mlog.info("alarmcallback...9");
            mlog.info("alarmcallback读取流已人为终止!--2" + ex.message, ex);
            try
            {
              if (stream != null)
              {
                stream.close();
                stream.dispose();
                response.close();
              }
            }
            catch
            {
            }
          }
          catch (system.exception ex)
          {
            mlog.info("alarmcallback...10");
             mlog.error("alarmcallback 0:" + ex.message,ex);
             try
             {
               if (stream != null)
               {
                 stream.close();
                 stream.dispose();
                 response.close();
               }
             }
             catch
             {
             }
             
            
          }
          finally
          {
            
          }
        }));
        alarmthead[1].isbackground = true;
        alarmthead[1].start();

      }
      catch (system.exception ex)
      {
        mlog.info("alarmcallback...11");
        mlog.error("alarmcallback 1:" + ex.message,ex);
        mlog.info("alarmcallback开始重新报警连接....3");
        mtimes = 50;
      }
      finally
      {
        
      }
    }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网