csharp-sdk-upm/Storage/Internal/Http/LCHttpClient.cs

218 lines
8.9 KiB
C#
Raw Normal View History

2020-02-19 18:50:51 +08:00
using System;
using System.Linq;
2020-02-19 18:50:51 +08:00
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Security.Cryptography;
2020-02-19 18:50:51 +08:00
using Newtonsoft.Json;
using LeanCloud.Common;
namespace LeanCloud.Storage.Internal.Http {
internal class LCHttpClient {
2020-03-09 12:31:25 +08:00
private readonly string appId;
2020-02-19 18:50:51 +08:00
readonly string appKey;
2020-02-19 18:50:51 +08:00
2020-03-09 12:31:25 +08:00
private readonly string server;
2020-02-19 18:50:51 +08:00
2020-03-09 12:31:25 +08:00
private readonly string sdkVersion;
2020-02-19 18:50:51 +08:00
readonly string apiVersion;
2020-02-19 18:50:51 +08:00
2020-03-09 12:31:25 +08:00
readonly AppRouter appRouter;
2020-02-19 18:50:51 +08:00
2020-03-09 12:31:25 +08:00
readonly HttpClient client;
readonly MD5 md5;
2020-02-19 18:50:51 +08:00
internal LCHttpClient(string appId, string appKey, string server, string sdkVersion, string apiVersion) {
this.appId = appId;
this.appKey = appKey;
this.server = server;
this.sdkVersion = sdkVersion;
this.apiVersion = apiVersion;
2020-03-09 12:31:25 +08:00
appRouter = new AppRouter(appId, server);
2020-02-19 18:50:51 +08:00
client = new HttpClient();
ProductHeaderValue product = new ProductHeaderValue("LeanCloud-CSharp-SDK", LeanCloud.SDKVersion);
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(product));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("X-LC-Id", appId);
md5 = MD5.Create();
2020-02-19 18:50:51 +08:00
}
internal async Task<T> Get<T>(string path,
Dictionary<string, object> headers = null,
Dictionary<string, object> queryParams = null) {
2020-03-09 12:31:25 +08:00
string url = await BuildUrl(path, queryParams);
HttpRequestMessage request = new HttpRequestMessage {
RequestUri = new Uri(url),
Method = HttpMethod.Get
};
await FillHeaders(request.Headers, headers);
HttpUtils.PrintRequest(client, request);
HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
request.Dispose();
string resultString = await response.Content.ReadAsStringAsync();
response.Dispose();
HttpUtils.PrintResponse(response, resultString);
if (response.IsSuccessStatusCode) {
T ret = JsonConvert.DeserializeObject<T>(resultString, new LeanCloudJsonConverter());
return ret;
}
throw HandleErrorResponse(response.StatusCode, resultString);
2020-02-19 18:50:51 +08:00
}
internal async Task<T> Post<T>(string path,
2020-02-19 18:50:51 +08:00
Dictionary<string, object> headers = null,
Dictionary<string, object> data = null,
Dictionary<string, object> queryParams = null) {
2020-03-09 12:31:25 +08:00
string url = await BuildUrl(path, queryParams);
2020-02-19 18:50:51 +08:00
HttpRequestMessage request = new HttpRequestMessage {
RequestUri = new Uri(url),
2020-02-19 18:50:51 +08:00
Method = HttpMethod.Post,
};
await FillHeaders(request.Headers, headers);
string content = null;
if (data != null) {
content = JsonConvert.SerializeObject(data);
StringContent requestContent = new StringContent(content);
requestContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = requestContent;
}
2020-02-19 18:50:51 +08:00
HttpUtils.PrintRequest(client, request, content);
HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
request.Dispose();
string resultString = await response.Content.ReadAsStringAsync();
response.Dispose();
HttpUtils.PrintResponse(response, resultString);
if (response.IsSuccessStatusCode) {
T ret = JsonConvert.DeserializeObject<T>(resultString, new LeanCloudJsonConverter());
return ret;
}
throw HandleErrorResponse(response.StatusCode, resultString);
}
internal async Task<T> Put<T>(string path,
Dictionary<string, object> headers = null,
Dictionary<string, object> data = null,
Dictionary<string, object> queryParams = null) {
2020-03-09 12:31:25 +08:00
string url = await BuildUrl(path, queryParams);
HttpRequestMessage request = new HttpRequestMessage {
RequestUri = new Uri(url),
Method = HttpMethod.Put,
};
await FillHeaders(request.Headers, headers);
string content = null;
if (data != null) {
content = JsonConvert.SerializeObject(data);
StringContent requestContent = new StringContent(content);
requestContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = requestContent;
}
HttpUtils.PrintRequest(client, request, content);
HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
request.Dispose();
string resultString = await response.Content.ReadAsStringAsync();
2020-02-19 18:50:51 +08:00
response.Dispose();
HttpUtils.PrintResponse(response, resultString);
if (response.IsSuccessStatusCode) {
T ret = JsonConvert.DeserializeObject<T>(resultString, new LeanCloudJsonConverter());
2020-02-19 18:50:51 +08:00
return ret;
}
throw HandleErrorResponse(response.StatusCode, resultString);
}
internal async Task Delete(string path) {
2020-03-09 12:31:25 +08:00
string url = await BuildUrl(path);
HttpRequestMessage request = new HttpRequestMessage {
RequestUri = new Uri(url),
Method = HttpMethod.Delete
};
await FillHeaders(request.Headers);
HttpUtils.PrintRequest(client, request);
HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
request.Dispose();
string resultString = await response.Content.ReadAsStringAsync();
response.Dispose();
HttpUtils.PrintResponse(response, resultString);
if (response.IsSuccessStatusCode) {
Dictionary<string, object> ret = JsonConvert.DeserializeObject<Dictionary<string, object>>(resultString, new LeanCloudJsonConverter());
return;
}
throw HandleErrorResponse(response.StatusCode, resultString);
}
LCException HandleErrorResponse(HttpStatusCode statusCode, string responseContent) {
int code = (int)statusCode;
string message = responseContent;
2020-02-19 18:50:51 +08:00
try {
// 尝试获取 LeanCloud 返回错误信息
Dictionary<string, object> error = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseContent, new LeanCloudJsonConverter());
2020-02-19 18:50:51 +08:00
code = (int)error["code"];
message = error["error"].ToString();
} catch (Exception e) {
Logger.Error(e.Message);
}
return new LCException(code, message);
}
2020-03-09 12:31:25 +08:00
async Task<string> BuildUrl(string path, Dictionary<string, object> queryParams = null) {
string apiServer = await appRouter.GetApiServer();
string url = $"{apiServer}/{apiVersion}/{path}";
if (queryParams != null) {
IEnumerable<string> queryPairs = queryParams.Select(kv => $"{kv.Key}={kv.Value}");
string queries = string.Join("&", queryPairs);
url = $"{url}?{queries}";
}
return url;
}
async Task FillHeaders(HttpRequestHeaders headers, Dictionary<string, object> additionalHeaders = null) {
// 额外 headers
if (additionalHeaders != null) {
foreach (KeyValuePair<string, object> kv in additionalHeaders) {
headers.Add(kv.Key, kv.Value.ToString());
}
}
// 签名
long timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
string data = $"{timestamp}{appKey}";
string hash = GetMd5Hash(md5, data);
string sign = $"{hash},{timestamp}";
headers.Add("X-LC-Sign", sign);
// 当前用户 Session Token
LCUser currentUser = await LCUser.GetCurrent();
if (currentUser != null) {
headers.Add("X-LC-Session", currentUser.SessionToken);
}
}
static string GetMd5Hash(MD5 md5Hash, string input) {
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < data.Length; i++) {
sb.Append(data[i].ToString("x2"));
}
return sb.ToString();
2020-02-19 18:50:51 +08:00
}
}
}