Пример #1
0
        /// <summary>
        /// 上传执行 方法
        /// </summary>
        /// <param name="parameter">上传文件请求参数</param>
        public static string Execute(UploadParameterType parameter)
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                // 1.分界线
                string boundary           = string.Format("----{0}", DateTime.Now.Ticks.ToString("x")), // 分界线可以自定义参数
                       beginBoundary      = string.Format("--{0}\r\n", boundary),
                       endBoundary        = string.Format("\r\n--{0}--\r\n", boundary);
                byte[] beginBoundaryBytes = parameter.Encoding.GetBytes(beginBoundary),
                endBoundaryBytes = parameter.Encoding.GetBytes(endBoundary);
                // 2.组装开始分界线数据体 到内存流中
                memoryStream.Write(beginBoundaryBytes, 0, beginBoundaryBytes.Length);
                // 3.组装 上传文件附加携带的参数 到内存流中
                if (parameter.PostParameters != null && parameter.PostParameters.Count > 0)
                {
                    foreach (KeyValuePair <string, string> keyValuePair in parameter.PostParameters)
                    {
                        string parameterHeaderTemplate = string.Format("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n{2}", keyValuePair.Key, keyValuePair.Value, beginBoundary);
                        byte[] parameterHeaderBytes    = parameter.Encoding.GetBytes(parameterHeaderTemplate);

                        memoryStream.Write(parameterHeaderBytes, 0, parameterHeaderBytes.Length);
                    }
                }
                // 4.组装文件头数据体 到内存流中
                string fileHeaderTemplate = string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n", parameter.FileNameKey, parameter.FileNameValue);
                byte[] fileHeaderBytes    = parameter.Encoding.GetBytes(fileHeaderTemplate);
                memoryStream.Write(fileHeaderBytes, 0, fileHeaderBytes.Length);
                // 5.组装文件流 到内存流中
                byte[] buffer = new byte[1024 * 1024 * 1];
                int    size   = parameter.UploadStream.Read(buffer, 0, buffer.Length);
                while (size > 0)
                {
                    memoryStream.Write(buffer, 0, size);
                    size = parameter.UploadStream.Read(buffer, 0, buffer.Length);
                }
                // 6.组装结束分界线数据体 到内存流中
                memoryStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
                // 7.获取二进制数据
                byte[] postBytes = memoryStream.ToArray();
                // 8.HttpWebRequest 组装
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(parameter.Url, UriKind.RelativeOrAbsolute));
                webRequest.Method        = "POST";
                webRequest.Timeout       = 10000;
                webRequest.ContentType   = string.Format("multipart/form-data; boundary={0}", boundary);
                webRequest.ContentLength = postBytes.Length;
                if (Regex.IsMatch(parameter.Url, "^https://"))
                {
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
                    ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
                }
                // 9.写入上传请求数据
                using (Stream requestStream = webRequest.GetRequestStream())
                {
                    requestStream.Write(postBytes, 0, postBytes.Length);
                    requestStream.Close();
                }
                // 10.获取响应
                using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
                {
                    using (StreamReader reader = new StreamReader(webResponse.GetResponseStream(), parameter.Encoding))
                    {
                        string body = reader.ReadToEnd();
                        reader.Close();
                        return(body);
                    }
                }
            }
        }
Пример #2
0
        static void Main(string[] args)
        {
            #region 创建访问服务的接口对象

            //TODO:
            //  集群配置【待完善】
            //HttpClusterApi = new HttpClusterApi();
            //HttpClusterApi.AddHost("*", "http://localhost:9090");

            //DemoService = HttpClusterApi.Create<IDemoController>();
            //AccountController = HttpClusterApi.Create<IAccountController>();
            //PublicController = HttpClusterApi.Create<IPublicController>();

            //非集群调用
            //实际运用时,DemoService、AccountController、PublicController 对象由容器中获得
            HttpApiClient client = new HttpApiClient("http://localhost:9090");
            DemoService       = client.Create <IDemoController>();
            AccountController = client.Create <IAccountController>();
            PublicController  = client.Create <IPublicController>();

            #endregion

            #region 测试服务的调用

            object result = null;

            Console.WriteLine("=======================GetQuestionList=======================");
            result = DemoService.GetQuestionList("test token info").Result;
            Console.WriteLine(result);

            Console.WriteLine("=======================Login=======================");
            result = AccountController.Login(new { userName = "******", password = "******", verifyCode = "sdh35" }).Result;
            Console.WriteLine(result);

            Console.WriteLine("=======================SayHello=======================");
            result = PublicController.SayHello("她是莉娜").Result;
            Console.WriteLine(result);

            Console.WriteLine("=======================GetJsonData=======================");
            result = PublicController.GetJsonData("犹似缘", "男", "你看你看月亮的脸").Result;
            Console.WriteLine(result);

            Console.WriteLine("=======================Post=======================");
            result = PublicController.Post(new { name = "諸葛冷冷", value = "30嵗" }).Result;
            Console.WriteLine(result);

            Console.WriteLine("=======================PostFormReturnJson=======================");
            result = PublicController.PostFormReturnJson("test111", "test222").Result;
            Console.WriteLine(result);

            Console.WriteLine("=======================PostForm=======================");
            result = PublicController.PostForm("觅尽尘缘", "哦耶").Result;
            Console.WriteLine(result);

            Console.WriteLine("=======================UploadFile=======================");
            //TODO:
            // 通過接口形式的文件上傳方式,在服務端暫時無法獲取文件流,等待詢問作者之後,給出正確方式
            var        fileUrl = "C:\\testfileupload.txt";
            FileStream fs      = new FileStream(fileUrl, FileMode.Open, FileAccess.Read);
            var        data    = new MultipartFormDataContent();
            data.Add(new StreamContent(fs));
            result = PublicController.UploadFile("这是一个配置文件", data).Result;
            Console.WriteLine(result);

            Console.WriteLine("=======================PostStream=======================");
            result = PublicController.PostStream("读取数据流:有些场需要读取数据流来转换自定义的数据,这种方式组件可以这样按以下方式来做").Result;
            result = HttpUtility.UrlDecode(result.ToString());
            Console.WriteLine(result);

            #endregion

            #region 测试文件的上传
            Console.WriteLine("=======================组装HTTP报文实现文件上传=======================");
            UploadParameterType parameters = new UploadParameterType();
            parameters.Url           = "http://localhost:9090/api/public/uploadfile";
            parameters.FileNameValue = "testfileupload.txt";
            parameters.UploadStream  = fs;
            parameters.PostParameters.Add("remark", "这是一个配置文件");
            var uploadResult = HttpUploadClient.Execute(parameters);
            Console.WriteLine(uploadResult);
            #endregion

            Console.ReadKey();
        }