zhaojs
2023-09-15 fc13938ff90213060532d99a600dea4a84456885
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
using Microsoft.AspNetCore.Hosting;
using Newtonsoft.Json;
using Steeltoe.Common.Discovery;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
 
namespace CommonUtil.Web
{
    /// <summary>
    /// 
    /// </summary>
    public class ServiceUtil
    {
        private readonly HttpClient client = new HttpClient();
        private readonly IHostingEnvironment hostingEnv;
        private IDiscoveryClient discClient;
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="discoveryClient"></param>
        /// <param name="hostingEnvironment"></param>
        public ServiceUtil(IDiscoveryClient discoveryClient, IHostingEnvironment hostingEnvironment)
        {
            DiscoveryHttpClientHandler _handler = new DiscoveryHttpClientHandler(discoveryClient);
            client = new HttpClient(_handler, false);
            hostingEnv = hostingEnvironment;
            discClient = discoveryClient;
        }
 
        /// <summary>
        /// Post请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="service"></param>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<T> PostAsync<T>(ServiceType service, string url, object data) where T : class, new()
        {
            try
            {
                string issandbox = ConfigUtil.Configuration["issandbox"] == null ? "" : ConfigUtil.Configuration["issandbox"];
                //请求地址
                if (hostingEnv.IsDevelopment() || (issandbox == "1"))
                {
                    url = ConfigUtil.Configuration[service.ToString()] + (url.StartsWith("/") ? "" : "/") + url;
                }
                else
                {
                    IList<IServiceInstance> disservice = discClient.GetInstances(service.ToString());
                    if (disservice.Count > 0)
                    {
                        int index = new Random().Next(0, disservice.Count);
                        url = "http://" + disservice[index].Host + ":" + disservice[index].Port + (url.StartsWith("/") ? "" : "/") + url;
                    }
                    else
                    {
                        url = "http://" + service.ToString() + (url.StartsWith("/") ? "" : "/") + url;
                    }
                    //url = "http://" + service.ToString() + (url.StartsWith("/") ? "" : "/") + url;
                }
                string content = "";
                if (data is string)
                {
                    content = data.ToString();
                }
                else
                {
                    content = JsonConvert.SerializeObject(data);
                }
 
                ByteArrayContent byteContent = null;
                if (service.ToString().StartsWith("wx."))
                {
                    Dictionary<string, object> dicJsonData = JsonConvert.DeserializeObject<Dictionary<string, object>>(content);
                    string postcontent = "";
                    foreach (string k in dicJsonData.Keys)
                    {
                        if (postcontent == "")
                        {
                            postcontent = k + "=" + (dicJsonData[k] == null ? "" : dicJsonData[k].ToString());
                        }
                        else
                        {
                            postcontent += "&" + k + "=" + (dicJsonData[k] == null ? "" : dicJsonData[k].ToString());
                        }
                    }
                    var buffer = Encoding.UTF8.GetBytes(postcontent);
                    byteContent = new ByteArrayContent(buffer);
                    byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                }
                else
                {
                    var buffer = Encoding.UTF8.GetBytes(content);
                    byteContent = new ByteArrayContent(buffer);
                    byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                }
                var response = await client.PostAsync(url, byteContent).ConfigureAwait(false);
                string result = await response.Content.ReadAsStringAsync();
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return new T();
                }
                return JsonConvert.DeserializeObject<T>(result);
            }
            catch (WebException ex)
            {
                throw new Exception("请求url:" + url + ",错误信息:" + ex.Message);
            }
        }
 
 
        /// <summary>
        /// Post请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<T> PostAsync<T>(string url, object data) where T : class, new()
        {
            try
            {
                string content = JsonConvert.SerializeObject(data);
                var buffer = Encoding.UTF8.GetBytes(content);
                var byteContent = new ByteArrayContent(buffer);
                byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                var response = await client.PostAsync(url, byteContent).ConfigureAwait(false);
                string result = await response.Content.ReadAsStringAsync();
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return new T();
                }
                return JsonConvert.DeserializeObject<T>(result);
            }
            catch (WebException ex)
            {
                if (ex.Response != null)
                {
                    string responseContent = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
                    throw new System.Exception($"response :{responseContent}", ex);
                }
                throw;
            }
        }
 
 
        /// <summary>
        /// 公共微服务类型
        /// </summary>
        public enum ServiceType
        {
            /// <summary>
            /// 文件服务
            /// </summary>
            crmfile,
            /// <summary>
            /// MQ服务
            /// </summary>
            crmrabbitmq,
            /// <summary>
            /// 缓存服务
            /// </summary>
            crm_memcache
        }
    }
}