1. 程式人生 > >C# 傳送xml報文到用友U8生成憑證系列二(基礎程式碼)

C# 傳送xml報文到用友U8生成憑證系列二(基礎程式碼)

上文我們詳細講解了u8voucher.xml、Web.config、U8EAI.asmx、EAIHandler.cs 等程式碼及xml報文格式及相關config配置等,接下來我們將講解Config、Route、Common 目錄下的類怎麼編寫的:

config目錄下的檔案:

appSetting.config程式碼:

這裡是配置的用友U8的eai報文匯入生成憑證的資訊

http://192.168.110.21/u8eai/import.asp 根據你的用友U8安裝的伺服器IP來設定
<appSettings>
  <add key="url" value="http://192.168.110.21/u8eai/import.asp"/>
  <add key="encoding" value="utf-8"/>
  <add key="voucher" value="NC2U8.Biz.Convert.VoucherConvertor"/>
</appSettings>

U8Voucher.xsd  連結資料庫 表

Route 目錄下的程式碼:

Router.cs 程式碼:

using NC2U8.Biz.Convert;
using System;
using System.Collections.Generic;
using System.Web;

namespace NC2U8.Route
{
    public class Router
    {
        public IConvertor GetConvertor(string type)
        {
            string className = System.Configuration.ConfigurationManager.AppSettings[type];
            if (string.IsNullOrEmpty(className))
                throw new NotSupportedException("不存在的報文型別。傳入型別:"+type);

            IConvertor convertor = Activator.CreateInstance(Type.GetType(className)) as IConvertor;
            return convertor;
        }
    }
}

Common 目錄下的程式碼:

HttpHelper.cs 程式碼:

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web;

namespace NC2U8.Common
{
    public class HttpHelper
    {
        public static HttpWebResponse Post(string url,string data)
        {
            var request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            byte[] btData = Encoding.UTF8.GetBytes(data);
            request.ContentLength = btData.Length;
            using(var stream = request.GetRequestStream())
            {
                stream.Write(btData, 0, btData.Length);
            }
            return request.GetResponse() as HttpWebResponse;
        }

        public static string GetResponseContent(HttpWebResponse response, string encodingName)
        {
            byte[] buffer = new byte[4096];
            using (Stream stream = response.GetResponseStream())
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    int count = 0;
                    while ((count = stream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        ms.Write(buffer, 0, count);
                    }
                    Encoding ec = Encoding.GetEncoding(encodingName);
                    string content = ec.GetString(ms.ToArray());
                    return content;
                }
            }
        }
    }
}

Ok 這些程式碼寫完,接下來下一篇文章將要講解最重要的環節程式碼:怎麼轉換XML節點為U8憑證。