HttpHelper类的调用方法详解

本文实例为大家分享了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
      {

      }
    }

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

(0)

相关推荐

  • C#使用Process类调用外部程序分解

    在程序开发中,一个程序经常需要去调用其他的程序,C#中Process类正好提供了这样的功能.它提供对本地和远程进程的访问并使您能够启动和停止本地系统进程. 一.启动进程实例 复制代码 代码如下: Process myProcess = new Process();   try  {       myProcess.StartInfo.UseShellExecute = false;       myProcess.StartInfo.FileName = "test.exe";    

  • C#中调用VB中Inputbox类的实现方法

    C#自己没有Inputbox这个类,但是Inputbox也蛮好用的,所以有两种方法可以使用 一:间接调用vb中的Inputbox功能 1.在项目中添加对Microsoft.VisualBasic引用       2.在项目中添加命名空间Using Microsoft.VisualBasic;       3.以后就可以直接使用VB中的好多类库(爽啊--) 例如:textBox1.Text=Microsoft.VisualBasic.Interaction.InputBox("提示性文字"

  • C#中派生类调用基类构造函数用法分析

    本文实例讲述了C#中派生类调用基类构造函数用法.分享给大家供大家参考.具体分析如下: 这里的默认构造函数是指在没有编写构造函数的情况下系统默认的无参构造函数 1.当基类中没有自己编写构造函数时,派生类默认的调用基类的默认构造函数 例如: public class MyBaseClass { } public class MyDerivedClass : MyBaseClass { public MyDerivedClass() { Console.WriteLine("我是子类无参构造函数&qu

  • C#中子类调用父类的实现方法

    本文实例讲述了C#中实现子类调用父类的方法,分享给大家供大家参考之用.具体方法如下: 一.通过子类无参构造函数创建子类实例 创建父类Person和子类Student. public class Person { public Person() { Console.WriteLine("我是人"); } } public class Student : Person { public Student() { Console.WriteLine("我是学生"); } }

  • C#调用mmpeg进行各种视频转换的类实例

    本文实例讲述了C#调用mmpeg进行各种视频转换的类.分享给大家供大家参考.具体如下: 这个C#类封装了视频转换所需的各种方法,基本上是围绕着如何通过mmpeg工具来进行视频转换 using System.Web; using System.Configuration; namespace DotNet.Utilities { //if (this.fload.HasFile) //{ // string upFileName = HttpContext.Current.Server.MapPa

  • PHP调用C#开发的dll类库方法

    有的时候,我们需要在php中利用到其他语言编写的dll类库,如C#编写的dll,方法就是利用PHP new COM方法来调用,在调用之前先要把dll库注册并把程序集放入到全局缓存中. 1. 创建一个 C# Class Library ,命名为:HelloWorld 2. 打开项目的属性,在点选左边的 "Application"(就是第一个tab) , 然后点击Assembly Information 按钮 ,在弹出的Dialog中, 必须在底部勾上: Make assembly COM

  • C#调用C++版本dll时的类型转换需要注意的问题小结

    C#对于C++的dll引用时,经常会遇到类型转换和struct的转换 1. C++ 里的Char类型是1 个字节,c#里的Char是两个字节,不可以对应使用:可使用c#里的byte对应 2. structType temp = (structType)Marshal.PtrToStructure(IntPtr, typeof(structType));说明:此方式转换只针对包含c++基本类型的结构体,如果包含指针数组的结构体,使用泛型函数比较方便. 3. [StructLayoutAttribu

  • C#调用Java类的实现方法

    一.将已经编译后的java中Class文件进行打包:打包命令JAR 如:将某目录下的所有class文件夹全部进行打包处理:使用的命令:jar cvf test.jar -C com/ .其中test.jar为要生成的jar包:com/ . 为指定的当前目录下的文件夹,该文件夹包括子文件夹及class文件: 二.到IKVM官方网站下载IKVM需要的组件  http://www.ikvm.net/ ikvm-0.42.0.3.zip ikvmbin-0.42.0.3.zip openjdk6-b16

  • SQL Server中调用C#类中的方法实例(使用.NET程序集)

    需求是这样的,我在.net程序里操作数据时将一些字段数据加密了,这些数据是很多系统共用的,其中一delphi程序也需要用到,并且需要将数据解密,由于我在.net里加密的方式比较特殊,在delphi程序里解密比较繁琐且要消耗很多时间,所以不得不让sqlserver调用程序集的方式来解决问题. 下面只是一个例子,贴出来共享. 建立一个dll,class,代码如下: 复制代码 代码如下: namespace MyDll {     public partial class MyClass     {

  • C#使用Process类调用外部exe程序

    在编写程序时经常会使用到调用可执行程序的情况,本文将简单介绍C#调用exe的方法.在C#中,通过Process类来进行进程操作. Process类在System.Diagnostics包中. 示例一 复制代码 代码如下: using System.Diagnostics; Process p = Process.Start("notepad.exe"); p.WaitForExit();//关键,等待外部程序退出后才能往下执行 通过上述代码可以调用记事本程序,注意如果不是调用系统程序,

随机推荐