HttpHelper.cs
7.32 KB
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
namespace Infrastructure
{
/// <summary>
/// http请求类
/// </summary>
public class HttpHelper
{
private HttpClient _httpClient;
private string _baseIPAddress;
private ICacheContext _cacheContext;
public string usertoken;
public HttpHelper(string ipaddress = "")
{
this._baseIPAddress = ipaddress;
_httpClient = new HttpClient { BaseAddress = new Uri(_baseIPAddress) };
}
/// <summary>
/// 创建带用户信息的请求客户端
/// </summary>
/// <param name="userName">用户账号</param>
/// <param name="pwd">用户密码,当WebApi端不要求密码验证时,可传空串</param>
/// <param name="uriString">The URI string.</param>
public HttpHelper(string userName, string pwd = "", string uriString = "")
: this(uriString)
{
if (!string.IsNullOrEmpty(userName))
{
_httpClient.DefaultRequestHeaders.Authorization = CreateBasicCredentials(userName, pwd);
}
}
/// <summary>
/// Get请求数据
/// /// <para>最终以url参数的方式提交</para>
/// <para>重构与post同样异步调用</para>
/// </summary>
/// <param name="parameters">参数字典,可为空</param>
/// <param name="requestUri">例如/api/Files/UploadFile</param>
/// <returns></returns>
public string Get(Dictionary<string, string> parameters, string requestUri)
{
if (parameters != null)
{
var strParam = string.Join("&", parameters.Select(o => o.Key + "=" + o.Value));
requestUri = string.Concat(ConcatURL(requestUri), '?', strParam);
}
else
{
requestUri = ConcatURL(requestUri);
}
var result = _httpClient.GetStringAsync(requestUri);
return result.Result;
}
/// <summary>
/// Get请求数据
/// <para>最终以url参数的方式提交</para>
/// </summary>
/// <param name="parameters">参数字典</param>
/// <param name="requestUri">例如/api/Files/UploadFile</param>
/// <returns>实体对象</returns>
public T Get<T>(Dictionary<string, string> parameters, string requestUri) where T : class
{
string jsonString = Get(parameters, requestUri);
if (string.IsNullOrEmpty(jsonString))
return null;
return JsonHelper.Instance.Deserialize<T>(jsonString);
}
/// <summary>
/// 以json的方式Post数据 返回string类型
/// <para>最终以json的方式放置在http体中</para>
/// </summary>
/// <param name="entity">实体</param>
/// <param name="requestUri">例如/api/Files/UploadFile</param>
/// <returns></returns>
public string Post(object entity, string requestUri)
{
string request = string.Empty;
if (entity != null)
request = JsonHelper.Instance.Serialize(entity);
HttpContent httpContent = new StringContent(request);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return Post(requestUri, httpContent);
}
/// <summary>
/// 提交字典类型的数据
/// <para>最终以formurlencode的方式放置在http体中</para>
/// </summary>
/// <returns>System.String.</returns>
public string PostDicObj(Dictionary<string, object> para, string requestUri)
{
Dictionary<string, string> temp = new Dictionary<string, string>();
foreach (var item in para)
{
if (item.Value != null)
{
if (item.Value.GetType().Name.ToLower() != "string")
{
temp.Add(item.Key, JsonHelper.Instance.Serialize(item.Value));
}
else
{
temp.Add(item.Key, item.Value.ToString());
}
}
else
{
temp.Add(item.Key, "");
}
}
return PostDic(temp, requestUri);
}
/// <summary>
/// Post Dic数据
/// <para>最终以formurlencode的方式放置在http体中</para>
/// </summary>
/// <returns>System.String.</returns>
public string PostDic(Dictionary<string, string> temp, string requestUri)
{
HttpContent httpContent = new FormUrlEncodedContent(temp);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
return Post(requestUri, httpContent);
}
public string PostByte(byte[] bytes, string requestUrl)
{
HttpContent content = new ByteArrayContent(bytes);
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return Post(requestUrl, content);
}
private string Post(string requestUrl, HttpContent content)
{
var result = _httpClient.PostAsync(ConcatURL(requestUrl), content);
return result.Result.Content.ReadAsStringAsync().Result;
}
private AuthenticationHeaderValue CreateBasicCredentials(string userName, string password)
{
string toEncode = userName + ":" + password;
// The current HTTP specification says characters here are ISO-8859-1.
// However, the draft specification for the next version of HTTP indicates this encoding is infrequently
// used in practice and defines behavior only for ASCII.
Encoding encoding = Encoding.GetEncoding("utf-8");
byte[] toBase64 = encoding.GetBytes(toEncode);
string parameter = Convert.ToBase64String(toBase64);
return new AuthenticationHeaderValue("Basic", parameter);
}
/// <summary>
/// 以json的方式Post数据 返回string类型
/// <para>最终以json的方式放置在http体中</para>
/// </summary>
/// <param name="entity">实体</param>
/// <param name="requestUri">例如/api/Files/UploadFile</param>
/// <returns></returns>
///
public string Post(string parameter, string requestUri)
{
HttpContent httpContent = new StringContent(parameter);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return Post(requestUri, httpContent);
}
/// <summary>
/// 把请求的URL相对路径组合成绝对路径
/// </summary>
private string ConcatURL(string requestUrl)
{
return new Uri(_httpClient.BaseAddress, requestUrl).OriginalString;
}
public HttpHelper(string ipaddress, ICacheContext cacheContext)
{
this._baseIPAddress = ipaddress;
_httpClient = new HttpClient { BaseAddress = new Uri(_baseIPAddress) };
_cacheContext = cacheContext;
}
}
}