using System.Xml.Serialization;
using Microsoft.AspNetCore.Mvc;
using XCGWebApp.Dtos;
using XCGWebApp.Common;
using System.Text;

namespace XCGWebApp.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class ReqController : ControllerBase
    {
        /// <summary>
        /// 接收字符串或者xml
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult AcceptXMLOrString()
        {
            var len = Convert.ToInt32(HttpContext.Request.ContentLength);
            byte[] byt = new byte[len];
            var ri = HttpContext.Request.BodyReader.AsStream().Read(byt, 0, len);
            string str = Encoding.UTF8.GetString(byt, 0, len);

            //如果传的是xml字符串,反序列化成对象。
            ReqDto? dto = null;
            XmlSerializer serializer = new XmlSerializer(typeof(ReqDto));
            using (StringReader sr = new StringReader(str))
            {
                object? obj = serializer.Deserialize(sr);
                if (obj != null)
                {
                    dto = (ReqDto)obj;
                }
            }

            ApiResult<object> result = new ApiResult<object>()
            {
                errorCode = "0",
                message = "success",
                data = dto
            };
            return new JsonResult(result);
        }

        /// <summary>
        /// /Req/SendXML
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> SendXML()
        {
            ApiResult<string> result = new ApiResult<string>()
            {
                errorCode = "0",
                message = "success",
                data = ""
            };
            string xmlStr = "";
            var dto = new ReqDto() { ErrorCode = 200, ReqName = "test" };
            XmlSerializer serializer = new XmlSerializer(typeof(ReqDto));
            using (StringWriter textWriter = new StringWriter())
            {
                serializer.Serialize(textWriter, dto);
                xmlStr = textWriter.ToString();
            }
            string url = "http://localhost:32831/Req/AcceptXMLOrString";
            var res = await ReqUtil.SendRequestXML(url, HttpMethod.Post, xmlStr);
            result.data = res.ToString();
            return new JsonResult(result);
        }
    }
}

 ReqUtil

using System.Net.Http.Headers;
using System.Text.Json;
using System.Text;

namespace XCGWebApp.Common
{
    public class ReqUtil
    {
        /// <summary>
        /// 发送请求
        /// </summary>
        public static async Task<string> SendRequestJSON(string url, HttpMethod method, string token, string data)
        {
            return await SendRequest(url, method, token, data, "application/json", "application/json");
        }
        /// <summary>
        /// 发送请求
        /// </summary>
        public static async Task<string> SendRequestJSON(string url, HttpMethod method, string data)
        {
            return await SendRequest(url, method, "", data, "application/json", "application/json");
        }
        /// <summary>
        /// 发送请求XML
        /// text/plain; charset=UTF-8
        /// </summary>
        public static async Task<string> SendRequestXML(string url, HttpMethod method, string data)
        {
            return await SendRequest(url, method, "", data, "application/xml", "application/json");
        }
        /// <summary>
        /// 发送请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="method"></param>
        /// <param name="token"></param>
        /// <param name="data"></param>
        /// <param name="sendMediaType">"application/json" / "text/xml; charset=UTF-8"</param>
        /// <param name="acceptMediaType">"application/json"</param>
        /// <returns></returns>
        public static async Task<string> SendRequest(string url, HttpMethod method, string token, string data, string sendMediaType = "application/json", string acceptMediaType = "application/json")
        {
            using HttpClient httpClient = new HttpClient();
            if (!string.IsNullOrEmpty(token))
            {
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
            }
            httpClient.Timeout = TimeSpan.FromSeconds(10);

            using HttpRequestMessage request = new HttpRequestMessage(method, url);
            request.Content = new StringContent(data, Encoding.UTF8, sendMediaType);
            request.Headers.Add("Accept", acceptMediaType);

            var httpResponseMessage = await httpClient.SendAsync(request).ConfigureAwait(false);
            if (httpResponseMessage.IsSuccessStatusCode)
            {
                string res = await httpResponseMessage.Content.ReadAsStringAsync();
                return res;
            }
            else
            {
                var obj = new ApiResult<object>()
                {
                    data = null,
                    errorCode = httpResponseMessage.StatusCode.ToString(),
                    message = "发送请求失败"
                };
                return JsonSerializer.Serialize(obj);
            }
        }

        /// <summary>
        /// 下载文件-带进度报告
        /// </summary>
        /// <param name="url"></param>
        /// <param name="targetPath"></param>
        /// <param name="progress"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static async Task DownloadFileAsync(string url, string targetPath, IProgress<HttpDownloadProgress> progress, CancellationToken token)
        {
            //var filePath = "D:\test.txt";
            if (File.Exists(targetPath))
            {
                File.Delete(targetPath);
            }
            System.Net.Http.HttpClient _client = new System.Net.Http.HttpClient();
            var bytes = await _client.GetByteArrayAsync(new Uri(url), progress, token);
            using var fileStream = new FileStream(targetPath, FileMode.Create);
            fileStream.Write(bytes, 0, bytes.Length);
        }
    }
}

 

posted on 2024-03-08 15:39  邢帅杰  阅读(168)  评论(0编辑  收藏  举报