bugfix : 解决外网下载文件问题

This commit is contained in:
范露尧
2023-02-14 11:35:23 +08:00
parent b8c9f1f552
commit 923622a4bb
14 changed files with 753 additions and 64 deletions

View File

@@ -4,6 +4,10 @@
<TargetFramework>net5.0</TargetFramework> <TargetFramework>net5.0</TargetFramework>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Furion" Version="4.8.6.2" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Getf_Service_Transfer_Client_coreService\Getf_Service_Transfer_Client_coreService.csproj" /> <ProjectReference Include="..\Getf_Service_Transfer_Client_coreService\Getf_Service_Transfer_Client_coreService.csproj" />
</ItemGroup> </ItemGroup>

View File

@@ -24,7 +24,7 @@ namespace Getf_Service_Transfer_Client_Service_HttpHandler
var url = action; var url = action;
HttpService httpService = new HttpService(); HttpService httpService = new HttpService();
var jsonStr = String.IsNullOrWhiteSpace(srcData.Body.Param) ? "{}" : srcData.Body.Param; var jsonStr = String.IsNullOrWhiteSpace(srcData.Body.Param) ? "{}" : srcData.Body.Param;
var rData = httpService.DoRequest(url, JsonConvert.DeserializeObject<JObject>(jsonStr), out string msg); var rData = httpService.DoRequest(url, JsonConvert.DeserializeObject<JObject>(jsonStr), srcData.Data, out string msg);
if (rData == null) if (rData == null)
{ {
r.TransResultInfo = new TransResult() r.TransResultInfo = new TransResult()

View File

@@ -21,9 +21,10 @@ namespace Getf_Service_Transfer_Client_Service_HttpHandler
return r; return r;
} }
var url = action; var url = action;
HttpService httpService = new HttpService(); //HttpService httpService = new HttpService();
var httpService = new HttpWebService();
var jsonStr = String.IsNullOrWhiteSpace(srcData.Body.Param) ? "{}" : srcData.Body.Param; var jsonStr = String.IsNullOrWhiteSpace(srcData.Body.Param) ? "{}" : srcData.Body.Param;
var rData = httpService.DoRequest(url, JsonConvert.DeserializeObject<JObject>(jsonStr), out string msg); var rData = httpService.DoRequest(url, JsonConvert.DeserializeObject<JObject>(jsonStr), srcData.Data, out string msg);
if (rData == null) if (rData == null)
{ {
r.TransResultInfo = new TransResult() r.TransResultInfo = new TransResult()

View File

@@ -1,4 +1,6 @@
using Getf_Service_Transfer_Client_coreService.Helpers; using Getf_Service_Transfer_Client_coreService.Entities;
using Getf_Service_Transfer_Client_coreService.Helpers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@@ -21,7 +23,7 @@ namespace Getf_Service_Transfer_Client_Service_HttpHandler
_LogHelper = new LogHelper(); _LogHelper = new LogHelper();
} }
public object DoRequest(string url, JObject jObject, out string msg) public object DoRequest(string url, JObject jObject, byte[] data, out string msg)
{ {
msg = String.Empty; msg = String.Empty;
try try
@@ -37,8 +39,6 @@ namespace Getf_Service_Transfer_Client_Service_HttpHandler
_LogHelper.Info($"93段接口url:{url}"); _LogHelper.Info($"93段接口url:{url}");
} }
HttpWebRequest httpWebRequest = WebRequest.Create(url) as HttpWebRequest; HttpWebRequest httpWebRequest = WebRequest.Create(url) as HttpWebRequest;
var head = jObject["Head"];
Encoding encoding = new UTF8Encoding(false); Encoding encoding = new UTF8Encoding(false);
if (jObject["Encoding"] != null) if (jObject["Encoding"] != null)
{ {
@@ -48,19 +48,49 @@ namespace Getf_Service_Transfer_Client_Service_HttpHandler
{ {
httpWebRequest.ContentType = jObject["ContentType"].Value<string>(); httpWebRequest.ContentType = jObject["ContentType"].Value<string>();
} }
httpWebRequest.Method = method;
SetHead(httpWebRequest, method, head); if (data.Length == 0)
{
var head = jObject["Head"];
SetHead(httpWebRequest, method, head);
}
object r; object r;
if (!"GET".Equals(method, StringComparison.OrdinalIgnoreCase)) if (!"GET".Equals(method, StringComparison.OrdinalIgnoreCase))
{ {
using (var requestStream = httpWebRequest.GetRequestStream()) using var requestStream = httpWebRequest.GetRequestStream();
if (data.Length > 0)
{ {
SetPostRequestStream(httpWebRequest, requestStream, jObject, encoding); var bodyIndex = GetBodyIndex(data);
r = GetResponse(httpWebRequest, encoding); var headBytes = data.Take(bodyIndex).ToArray();
requestStream.Close(); var headStr = encoding.GetString(headBytes);
requestStream.Dispose(); SetHead(httpWebRequest, method, headStr);
string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
//httpWebRequest.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
requestStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
//requestStream.Write(headBytes, 0, headBytes.Length);
var bodyData = data.Skip(bodyIndex)/*.Select(m => (char)m)*/.ToArray();
requestStream.Write(bodyData, 0, bodyData.Length);
requestStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
//var bodyIndex = GetBodyIndex(data);
//var headStr = encoding.GetString(data.Take(bodyIndex).ToArray());
//SetHead(httpWebRequest, method, headStr);
//var bodyData = data.Skip(bodyIndex)/*.Select(m => (char)m)*/.ToArray();
//requestStream.Write(bodyData, 0, bodyData.Length);
////Bytes2File(bodyData, "", "11.zip");
////requestStream.Write(data, 0, data.Length);
} }
else
SetPostRequestStream(httpWebRequest, requestStream, jObject, encoding);
r = GetResponse(httpWebRequest, encoding);
requestStream.Close();
requestStream.Dispose();
} }
else else
{ {
@@ -106,6 +136,50 @@ namespace Getf_Service_Transfer_Client_Service_HttpHandler
} }
return null; return null;
} }
/// <summary>
/// 将byte数组转换为文件并保存到指定地址
/// </summary>
/// <param name="buff">byte数组</param>
/// <param name="savepath">保存地址</param>
public void Bytes2File(byte[] buff, string savepath, string fileName)
{
try
{
//如果不存在就创建Enclosure文件夹
if (Directory.Exists(savepath + @"\Enclosure\") == false)
{
Directory.CreateDirectory(savepath + @"\Enclosure\");
}
if (System.IO.File.Exists(savepath + @"\Enclosure\" + fileName))
{
System.IO.File.Delete(savepath + @"\Enclosure\" + fileName);
}
FileStream fs = new FileStream(savepath + @"\Enclosure\" + fileName, FileMode.CreateNew);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(buff, 0, buff.Length);
bw.Close();
fs.Close();
}
catch (Exception)
{
}
}
private int GetBodyIndex(byte[] data)
{
var index = -1;
for (int i = 0, c = data.Length; i < c; i++)
{
var elem = data[i];
if (elem == '\r' && i + 3 < data.Length && data[i + 1] == '\n' && data[i + 2] == '\r' && data[i + 3] == '\n')
{
index = i + 4;
break;
}
}
return index;
}
private string GetGetUrl(string url, JObject jObject) private string GetGetUrl(string url, JObject jObject)
{ {
if (!url.Contains("?")) url += "?1=1"; if (!url.Contains("?")) url += "?1=1";
@@ -170,12 +244,37 @@ namespace Getf_Service_Transfer_Client_Service_HttpHandler
} }
} }
private void SetHead(HttpWebRequest httpWebRequest, string method, string headStr)
{
httpWebRequest.Method = method;
var headStrSplitResult = headStr.Split(new String[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var elem in headStrSplitResult)
{
var keyValue = elem.Split(':');
var name = keyValue[0];
var value = keyValue[1];
if ("Accept-Encoding".Equals(name, StringComparison.OrdinalIgnoreCase))
{
httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip;
}
SetHeaderValue(httpWebRequest.Headers, name, value);
}
/*if ("post".Equals(method, StringComparison.OrdinalIgnoreCase))
{
if (String.IsNullOrWhiteSpace(httpWebRequest.ContentType))
{
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
}
}*/
}
private void SetPostRequestStream(HttpWebRequest httpWebRequest, Stream requestStream, JObject jObject, Encoding encoding) private void SetPostRequestStream(HttpWebRequest httpWebRequest, Stream requestStream, JObject jObject, Encoding encoding)
{ {
using (var streamWrite = new StreamWriter(requestStream, encoding)) using (var streamWrite = new StreamWriter(requestStream, encoding))
{ {
var param = jObject["Param"]?.Value<string>() ?? String.Empty; var param = jObject["Param"]?.Value<string>() ?? String.Empty;
streamWrite.Write(param); if (!string.IsNullOrEmpty(param))
streamWrite.Write(param);
var jdata = jObject["Data"]; var jdata = jObject["Data"];
if (jdata != null) if (jdata != null)

View File

@@ -0,0 +1,289 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Getf_Service_Transfer_Client_coreService.Entities;
using Getf_Service_Transfer_Client_coreService;
using Getf_Service_Transfer_Client_Service_HttpHandler;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using Getf_Service_Transfer_Client_coreService.Helpers;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Reflection;
using System.Net.Http;
using Furion.RemoteRequest.Extensions;
using Furion.RemoteRequest;
namespace Getf_Service_Transfer_Client_Service_HttpHandler
{
public class HttpWebService
{
LogHelper _LogHelper;
public HttpWebService()
{
_LogHelper = new LogHelper();
}
public object DoRequest(string url, JObject jObject, byte[] data, out string msg)
{
msg = String.Empty;
try
{
var method = HttpMethod.Post;
if (jObject["Method"] != null)
{
if ("GET".Equals(jObject["Method"].Value<string>(), StringComparison.OrdinalIgnoreCase))
{
method = HttpMethod.Get;
url = GetGetUrl(url, jObject);
_LogHelper.Info($"93段接口url:{url}");
}
}
var httpRequst = url.SetHttpMethod(method);
Encoding encoding = new UTF8Encoding(false);
if (jObject["Encoding"] != null)
{
httpRequst.SetContentEncoding(Encoding.GetEncoding(jObject["Encoding"].Value<string>()));
}
object r;
SetHead(httpRequst, jObject["Head"]);
httpRequst.SetBody(jObject["Data"].ToString());
if (data.Length > 0)
{
httpRequst.SetRequestUrl(url + "byte");
httpRequst.SetBody(new { FileName = jObject["Data"]["fileName"].ToString(), bytes = data });
}
var response = httpRequst.SendAsync().Result;
if (IsTextContentType(response.Content.Headers.ContentType.MediaType))
{
r = response.Content.ReadAsStringAsync().Result;
}
else
{
r = response.Content.ReadAsByteArrayAsync().Result;
}
_LogHelper.Info($"93段接口:method:{method},url:{url},参数:{jObject["Data"]},结果:{r}");
return r;
}
catch (WebException e)
{
_LogHelper.Info("异常:" + Newtonsoft.Json.JsonConvert.SerializeObject(e));
if (e?.Response != null)
{
using (var stream = e?.Response?.GetResponseStream())
{
msg = "http错误(" + (int)(e?.Response as HttpWebResponse)?.StatusCode + ")";
if (stream != null)
{
using (StreamReader streamReader = new StreamReader(stream))
{
msg += streamReader.ReadToEnd();
_LogHelper.Info("1:请求错误原因为:" + msg);
}
}
else
{
msg += e.Message;
_LogHelper.Info("2:请求错误原因为:" + msg);
}
}
}
else
{
msg += e.Message;
_LogHelper.Info("2:请求错误原因为:" + msg);
}
}
catch (Exception e)
{
msg = e.Message;
_LogHelper.Info("3:请求错误原因为:" + msg);
}
return null;
}
/// <summary>
/// 将byte数组转换为文件并保存到指定地址
/// </summary>
/// <param name="buff">byte数组</param>
/// <param name="savepath">保存地址</param>
public void Bytes2File(byte[] buff, string savepath, string fileName)
{
try
{
//如果不存在就创建Enclosure文件夹
if (Directory.Exists(savepath + @"\Enclosure\") == false)
{
Directory.CreateDirectory(savepath + @"\Enclosure\");
}
if (System.IO.File.Exists(savepath + @"\Enclosure\" + fileName))
{
System.IO.File.Delete(savepath + @"\Enclosure\" + fileName);
}
FileStream fs = new FileStream(savepath + @"\Enclosure\" + fileName, FileMode.CreateNew);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(buff, 0, buff.Length);
bw.Close();
fs.Close();
}
catch (Exception)
{
}
}
private int GetBodyIndex(byte[] data)
{
var index = -1;
for (int i = 0, c = data.Length; i < c; i++)
{
var elem = data[i];
if (elem == '\r' && i + 3 < data.Length && data[i + 1] == '\n' && data[i + 2] == '\r' && data[i + 3] == '\n')
{
index = i + 4;
break;
}
}
return index;
}
private string GetGetUrl(string url, JObject jObject)
{
if (!url.Contains("?")) url += "?1=1";
var jParam = jObject["Param"];
if (jParam != null)
{
var Param = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(jParam.ToString());
foreach (var item in Param)
{
url += $"&{item.Key}={item.Value}";
}
}
var jdata = jObject["Data"];
if (jdata != null)
{
var Data = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(jdata.ToString());
foreach (var item in Data)
{
if (item.Value is JArray)
{
foreach (var arr in (JArray)item.Value)
{
url += $"&{item.Key}={arr}";
}
}
else if (item.Value is JObject)
url += $"&{item.Key}={Newtonsoft.Json.JsonConvert.SerializeObject(item.Value)}";
else if (item.Value != null && !string.IsNullOrWhiteSpace(item.Value.ToString()))
url += $"&{item.Key}={item.Value}";
}
}
return url;
}
private static PropertyInfo InnerCollectionProperty = typeof(WebHeaderCollection).GetProperty("InnerCollection",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
public static void SetHeaderValue(WebHeaderCollection header, string name, string value)
{
var collection = InnerCollectionProperty.GetValue(header, null) as NameValueCollection;
collection[name] = value;
}
private void SetHead(HttpRequestPart httprequest, JToken head)
{
var dic = new Dictionary<string, object>();
if (head != null)
{
foreach (JProperty elem in head)
{
var name = elem.Name;
var value = elem.Value.ToString();
dic.Add(name, value);
}
}
httprequest.SetHeaders(dic);
}
private void SetHead(HttpWebRequest httpWebRequest, string method, string headStr)
{
httpWebRequest.Method = method;
var headStrSplitResult = headStr.Split(new String[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var elem in headStrSplitResult)
{
var keyValue = elem.Split(':');
var name = keyValue[0];
var value = keyValue[1];
if ("Accept-Encoding".Equals(name, StringComparison.OrdinalIgnoreCase))
{
httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip;
}
SetHeaderValue(httpWebRequest.Headers, name, value);
}
/*if ("post".Equals(method, StringComparison.OrdinalIgnoreCase))
{
if (String.IsNullOrWhiteSpace(httpWebRequest.ContentType))
{
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
}
}*/
}
private void SetPostRequestStream(HttpWebRequest httpWebRequest, Stream requestStream, JObject jObject, Encoding encoding)
{
using (var streamWrite = new StreamWriter(requestStream, encoding))
{
var param = jObject["Param"]?.Value<string>() ?? String.Empty;
if (!string.IsNullOrEmpty(param))
streamWrite.Write(param);
var jdata = jObject["Data"];
if (jdata != null)
{
var Data = jdata.ToString();
var _bytes = encoding.GetBytes(Data);
httpWebRequest.ContentLength = _bytes.Length;
requestStream.Write(_bytes, 0, _bytes.Length);
}
}
}
private static readonly string[] TextContentTypes = new string[] { "application/json", "text/html" };
private object GetResponse(HttpWebRequest httpWebRequest, Encoding encoding)
{
var response = httpWebRequest.GetResponse();
using (var stream = response.GetResponseStream())
{
if (IsTextContentType(response.ContentType))
{
using (StreamReader streamReader = new StreamReader(stream, encoding))
{
var r = streamReader.ReadToEnd();
return r;
}
}
else
{
using (MemoryStream ms = new MemoryStream())
{
stream.CopyTo(ms);
return ms.ToArray();
}
}
}
}
private bool IsTextContentType(string contentType)
{
if (contentType == null) return true;
contentType = contentType.ToLower();
var list = new string[] { "text/", "application/json", "application/xml" };
return list.Any(m => contentType.Contains(m));
}
}
}

View File

@@ -0,0 +1,289 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.TagHelpers;
using Newtonsoft.Json.Linq;
namespace Getf_Service_Transfer_Client_Service_HttpHandler
{
/// <summary>
/// 总结各种请求方式
/// </summary>
public class RequestWaysHelp
{
#region 01-WebClient的Get请求
/// <summary>
/// WebClient的Get请求
/// </summary>
/// <param name="url">请求地址,含拼接数据,请求格式为:"http://XXXX?userName=admin&pwd=123456";</param>
/// <returns></returns>
public static string WcGet(string url)
{
WebClient wc = new WebClient();
wc.Encoding = Encoding.UTF8;
return wc.DownloadString(url);
}
#endregion
#region 02-WebClient的Post请求
/// <summary>
/// WebClient的Post请求
/// 表单提交模式[application/x-www-form-urlencoded]
/// </summary>
/// <param name="url">请求地址,单纯的地址,没有数据拼接</param>
/// <param name="data">请求数据,格式为:"userName=admin&pwd=123456"</param>
/// <returns></returns>
public static string WcPost1(string url, string data)
{
WebClient wc = new WebClient();
wc.Encoding = Encoding.UTF8;
//也可以向表头中添加一些其他东西
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
return wc.UploadString(url, data);
}
#endregion
#region 03-WebClient的Post请求
/// <summary>
/// WebClient的Post请求
/// Json提交模式[application/json]
/// </summary>
/// <param name="url">请求地址,单纯的地址,没有数据拼接</param>
/// <param name="data">请求数据,格式为(Json)对象、或者类对象 eg new {id="1"}</param>
/// <returns></returns>
public static string WcPost2(string url, object data)
{
WebClient wc = new WebClient();
wc.Encoding = Encoding.UTF8;
//也可以向表头中添加一些其他东西
wc.Headers.Add("Content-Type", "application/json");
return wc.UploadString(url, Newtonsoft.Json.JsonConvert.SerializeObject(data));
}
#endregion
#region 04-HttpWebRequest的Get请求
/// <summary>
/// HttpWebRequest的Get请求
/// </summary>
/// <param name="url">请求地址,含拼接数据,请求格式为:"http://XXXX?userName=admin&pwd=123456";</param>
/// <returns></returns>
public static string HwGet(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 30 * 1000;
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36";
request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
string result = "";
using (var res = request.GetResponse() as HttpWebResponse)
{
if (res.StatusCode == HttpStatusCode.OK)
{
StreamReader reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
result = reader.ReadToEnd();
}
}
return result;
}
#endregion
#region 05-HttpWebRequest的Post请求
/// <summary>
/// HttpWebRequest的Post请求
/// 表单提交模式[application/x-www-form-urlencoded]
/// </summary>
/// <param name="url">请求地址,单纯的地址,没有数据拼接</param>
/// <param name="data">请求数据,格式为:"userName=admin&pwd=123456"</param>
/// <returns></returns>
public static string HwPost1(string url, string data)
{
var request = HttpWebRequest.Create(url) as HttpWebRequest;
request.Timeout = 30 * 1000;//设置30s的超时
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36";
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
byte[] data2 = Encoding.UTF8.GetBytes(data);
request.ContentLength = data2.Length;
Stream postStream = request.GetRequestStream();
postStream.Write(data2, 0, data2.Length);
postStream.Close();
string result = "";
using (var res = request.GetResponse() as HttpWebResponse)
{
if (res.StatusCode == HttpStatusCode.OK)
{
StreamReader reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
result = reader.ReadToEnd();
}
}
return result;
}
#endregion
#region 06-HttpWebRequest的Post请求
/// <summary>
/// HttpWebRequest的Post请求
/// Json提交模式[application/json]
/// </summary>
/// <param name="url">请求地址,单纯的地址,没有数据拼接</param>
/// <param name="data">请求数据,格式为(Json)对象、或者类对象 eg new {id="1"}</param>
/// <returns></returns>
public static string HwPost2(string url, object data)
{
var postData = Newtonsoft.Json.JsonConvert.SerializeObject(data);
var request = HttpWebRequest.Create(url) as HttpWebRequest;
request.Timeout = 30 * 1000; //设置30s的超时
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36";
request.ContentType = "application/json";
request.Method = "POST";
byte[] data2 = Encoding.UTF8.GetBytes(postData);
request.ContentLength = data2.Length;
Stream postStream = request.GetRequestStream();
postStream.Write(data2, 0, data2.Length);
postStream.Close();
string result = "";
using (var res = request.GetResponse() as HttpWebResponse)
{
if (res.StatusCode == HttpStatusCode.OK)
{
StreamReader reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
result = reader.ReadToEnd();
}
}
return result;
}
#endregion
#region 07-HttpClient的Get请求
/// <summary>
/// HttpClient的Get请求
/// </summary>
///<param name="url">请求地址,含拼接数据,请求格式为:"http://XXXX?userName=admin&pwd=123456";</param>
/// <returns></returns>
public static async Task<string> HcGet(string url)
{
var http = HttpClientFactory2.GetHttpClient();
var response1 = await http.GetAsync(url);
return await response1.Content.ReadAsStringAsync();
}
#endregion
#region 08-HttpClient的Post请求
/// <summary>
/// HttpClient的Post请求
/// 表单提交模式[application/x-www-form-urlencoded]
/// </summary>
/// <param name="url">请求地址,单纯的地址,没有数据拼接</param>
/// <param name="data">请求数据,格式为:"userName=admin&pwd=123456"</param>
/// <returns></returns>
public static async Task<string> HcPost(string url, string data)
{
var http = HttpClientFactory2.GetHttpClient();
var content = new StringContent(data, Encoding.UTF8, "application/x-www-form-urlencoded");
var response = await http.PostAsync(url, content);
return await response.Content.ReadAsStringAsync();
}
#endregion
#region 09-HttpClient的Post请求
/// <summary>
/// HttpClient的Post请求
/// Json提交模式[application/json]
/// </summary>
/// <param name="url">请求地址,单纯的地址,没有数据拼接</param>
/// <param name="data">请求数据,格式为(Json)对象、或者类对象 eg new {id="1"}</param>
/// <returns></returns>
public async static Task<string> HcPost(string url, object data)
{
var http = HttpClientFactory2.GetHttpClient();
var content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
var response = await http.PostAsync(url, content);
return await response.Content.ReadAsStringAsync();
}
#endregion
public static async Task<string> Request(string url, string method, JToken head, JToken data)
{
if (method.ToUpper().Trim() == "GET")
return await HcGet(url);
var http = HttpClientFactory2.GetHttpClient();
if (data == null)
{
data = "";
}
var content = new StringContent(data.ToString(), Encoding.UTF8, "application/json");
SetHead(http, method.ToUpper(), head);
var response = await http.PostAsync(url, content);
return await response.Content.ReadAsStringAsync();
}
public static async Task<string> Request(string url, string method, JToken head, List<byte[]> listbytes)
{
if (method.ToUpper().Trim() == "GET")
return await HcGet(url);
var http = HttpClientFactory2.GetHttpClient();
var formdata = new MultipartFormDataContent();
foreach (var item in listbytes)
{
if (item.Length > 0)
{
var byteContent = new ByteArrayContent(item);
formdata.Add(byteContent);
}
}
SetHead(http, method.ToUpper(), head);
var response = await http.PostAsync(url, formdata);
return await response.Content.ReadAsStringAsync();
}
private static void SetHead(HttpClient http, string method, JToken head)
{
if (head != null)
{
foreach (JProperty elem in head)
{
var name = elem.Name;
var value = elem.Value.ToString();
http.DefaultRequestHeaders.Add(name, value);
}
}
}
}
/// <summary>
/// 将HttpClient做成单例的不用Using全局只有一个
/// 来解决tcp连接不能释放的问题
/// </summary>
public class HttpClientFactory2
{
private static HttpClient _httpClient = null;
/// <summary>
/// 静态的构造函数:只能有一个,且是无参数的
/// 由CLR保证只有在程序第一次使用该类之前被调用而且只能调用一次
/// 说明: keep-alive关键字可以理解为一个长链接超时时间也可以在上面进行设置例如10秒的超时时间当然并发量太大这个10秒应该会抛弃很多请求
/// 发送请求的代码没有了using即这个httpclient不会被手动dispose而是由系统控制它当然你的程序重启时这也就被回收了。
/// </summary>
static HttpClientFactory2()
{
_httpClient = new HttpClient(new HttpClientHandler());
_httpClient.Timeout = new TimeSpan(0, 0, 10);
_httpClient.DefaultRequestHeaders.Connection.Add("keep-alive");
}
/// <summary>
/// 对外开放接口
/// </summary>
/// <returns></returns>
public static HttpClient GetHttpClient()
{
return _httpClient;
}
}
}

View File

@@ -44,6 +44,7 @@ namespace Getf_Service_Transfer_core_client
}; };
}); });
// services.AddHostedService<Worker>(); // services.AddHostedService<Worker>();
services.AddRemoteRequest();
})//配置log4net })//配置log4net
.ConfigureLogging(p => .ConfigureLogging(p =>
{ {

View File

@@ -9,9 +9,10 @@
<AppDesignerFolder>Properties</AppDesignerFolder> <AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Getf.Service.Transfer.Core</RootNamespace> <RootNamespace>Getf.Service.Transfer.Core</RootNamespace>
<AssemblyName>Getf.Service.Transfer.Core</AssemblyName> <AssemblyName>Getf.Service.Transfer.Core</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion> <TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic> <Deterministic>true</Deterministic>
<TargetFrameworkProfile />
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
@@ -21,6 +22,7 @@
<DefineConstants>DEBUG;TRACE</DefineConstants> <DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType> <DebugType>pdbonly</DebugType>
@@ -29,6 +31,7 @@
<DefineConstants>TRACE</DefineConstants> <DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="log4net, Version=1.2.13.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL"> <Reference Include="log4net, Version=1.2.13.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">

View File

@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<packages> <packages>
<package id="log4net" version="2.0.3" targetFramework="net40" /> <package id="log4net" version="2.0.3" targetFramework="net40" />
<package id="Newtonsoft.Json" version="12.0.1" targetFramework="net40" /> <package id="Newtonsoft.Json" version="12.0.1" targetFramework="net40" requireReinstallation="true" />
<package id="SuperSocket" version="1.6.6.1" targetFramework="net40" /> <package id="SuperSocket" version="1.6.6.1" targetFramework="net40" requireReinstallation="true" />
<package id="SuperSocket.Engine" version="1.6.6.1" targetFramework="net40" /> <package id="SuperSocket.Engine" version="1.6.6.1" targetFramework="net40" requireReinstallation="true" />
</packages> </packages>

View File

@@ -1,11 +1,11 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<configuration> <configuration>
<configSections> <configSections>
<section name="superSocket" type="SuperSocket.SocketEngine.Configuration.SocketServiceConfig, SuperSocket.SocketEngine" /> <section name="superSocket" type="SuperSocket.SocketEngine.Configuration.SocketServiceConfig, SuperSocket.SocketEngine"/>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections> </configSections>
<startup> <startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8"/>
</startup> </startup>
<appSettings> <appSettings>
<add key="IpInfo" value=":9999"/> <add key="IpInfo" value=":9999"/>

View File

@@ -8,7 +8,7 @@
<OutputType>WinExe</OutputType> <OutputType>WinExe</OutputType>
<RootNamespace>Getf.Service.Transfer.WinService</RootNamespace> <RootNamespace>Getf.Service.Transfer.WinService</RootNamespace>
<AssemblyName>Getf.Service.Transfer.WinService</AssemblyName> <AssemblyName>Getf.Service.Transfer.WinService</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic> <Deterministic>true</Deterministic>
<TargetFrameworkProfile /> <TargetFrameworkProfile />

View File

@@ -1,13 +1,13 @@
<?xml version="1.0" encoding="utf-8" ?> <?xml version="1.0" encoding="utf-8"?>
<configuration> <configuration>
<configSections> <configSections>
<section name="superSocket" type="SuperSocket.SocketEngine.Configuration.SocketServiceConfig, SuperSocket.SocketEngine" /> <section name="superSocket" type="SuperSocket.SocketEngine.Configuration.SocketServiceConfig, SuperSocket.SocketEngine"/>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections> </configSections>
<appSettings> <appSettings>
<add key="log4net.Internal.Debug" value="true "/> <add key="log4net.Internal.Debug" value="true "/>
<add key="AccountConfigPath" value="AccountConfig.xml" /> <add key="AccountConfigPath" value="AccountConfig.xml"/>
<add key="Port" value="8002" /> <add key="Port" value="8002"/>
</appSettings> </appSettings>
<superSocket> <superSocket>
<servers> <servers>
@@ -23,59 +23,59 @@
<appender-ref ref="ErrorAppender" /> <appender-ref ref="ErrorAppender" />
</logger>--> </logger>-->
<logger name="logall"> <logger name="logall">
<level value="ALL" /> <level value="ALL"/>
<appender-ref ref="ErrorAppender"/> <appender-ref ref="ErrorAppender"/>
<appender-ref ref="InfoAppender"/> <appender-ref ref="InfoAppender"/>
<appender-ref ref="DebugAppender"/> <appender-ref ref="DebugAppender"/>
</logger> </logger>
<appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender"> <appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="Log\\LogError\\" /> <param name="File" value="Log\\LogError\\"/>
<param name="AppendToFile" value="true" /> <param name="AppendToFile" value="true"/>
<param name="MaxSizeRollBackups" value="100" /> <param name="MaxSizeRollBackups" value="100"/>
<param name="MaxFileSize" value="10240" /> <param name="MaxFileSize" value="10240"/>
<param name="StaticLogFileName" value="false" /> <param name="StaticLogFileName" value="false"/>
<param name="DatePattern" value="yyyyMMdd&quot;.txt&quot;" /> <param name="DatePattern" value="yyyyMMdd&quot;.txt&quot;"/>
<param name="RollingStyle" value="Date" /> <param name="RollingStyle" value="Date"/>
<layout type="log4net.Layout.PatternLayout"> <layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%n异常时间%d %n异常级别%-5p%n异常内容%m%n" /> <param name="ConversionPattern" value="%n异常时间%d %n异常级别%-5p%n异常内容%m%n"/>
</layout> </layout>
<filter type="log4net.Filter.LevelRangeFilter"> <filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="ERROR" /> <param name="LevelMin" value="ERROR"/>
<param name="LevelMax" value="FATAL" /> <param name="LevelMax" value="FATAL"/>
</filter> </filter>
<!--&lt; &gt; = <> %n = 回车--> <!--&lt; &gt; = <> %n = 回车-->
</appender> </appender>
<appender name="InfoAppender" type="log4net.Appender.RollingFileAppender"> <appender name="InfoAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="Log\\LogInfo\\" /> <param name="File" value="Log\\LogInfo\\"/>
<param name="AppendToFile" value="true" /> <param name="AppendToFile" value="true"/>
<param name="MaxFileSize" value="10240" /> <param name="MaxFileSize" value="10240"/>
<param name="MaxSizeRollBackups" value="100" /> <param name="MaxSizeRollBackups" value="100"/>
<param name="StaticLogFileName" value="false" /> <param name="StaticLogFileName" value="false"/>
<param name="DatePattern" value="yyyyMMdd&quot;.txt&quot;" /> <param name="DatePattern" value="yyyyMMdd&quot;.txt&quot;"/>
<param name="RollingStyle" value="Date" /> <param name="RollingStyle" value="Date"/>
<layout type="log4net.Layout.PatternLayout"> <layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="日志时间:%d %n日志级别%-5p %n日志内容%m%n%n" /> <param name="ConversionPattern" value="日志时间:%d %n日志级别%-5p %n日志内容%m%n%n"/>
</layout> </layout>
<filter type="log4net.Filter.LevelRangeFilter"> <filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="INFO" /> <param name="LevelMin" value="INFO"/>
<param name="LevelMax" value="WARN" /> <param name="LevelMax" value="WARN"/>
</filter> </filter>
</appender> </appender>
<appender name="DebugAppender" type="log4net.Appender.RollingFileAppender"> <appender name="DebugAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="Log\\LogDebug\\" /> <param name="File" value="Log\\LogDebug\\"/>
<param name="AppendToFile" value="true" /> <param name="AppendToFile" value="true"/>
<param name="MaxFileSize" value="10240" /> <param name="MaxFileSize" value="10240"/>
<param name="MaxSizeRollBackups" value="100" /> <param name="MaxSizeRollBackups" value="100"/>
<param name="StaticLogFileName" value="false" /> <param name="StaticLogFileName" value="false"/>
<param name="DatePattern" value="yyyyMMdd&quot;.txt&quot;" /> <param name="DatePattern" value="yyyyMMdd&quot;.txt&quot;"/>
<param name="RollingStyle" value="Date" /> <param name="RollingStyle" value="Date"/>
<layout type="log4net.Layout.PatternLayout"> <layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="日志时间:%d %n日志级别%-5p %n日志内容%m%n%n" /> <param name="ConversionPattern" value="日志时间:%d %n日志级别%-5p %n日志内容%m%n%n"/>
</layout> </layout>
<filter type="log4net.Filter.LevelRangeFilter"> <filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="ALL" /> <param name="LevelMin" value="ALL"/>
<param name="LevelMax" value="DEBUG" /> <param name="LevelMax" value="DEBUG"/>
</filter> </filter>
</appender> </appender>
</log4net> </log4net>
</configuration> <startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8"/></startup></configuration>

View File

@@ -8,7 +8,7 @@
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<RootNamespace>Getf.Service.Transfer</RootNamespace> <RootNamespace>Getf.Service.Transfer</RootNamespace>
<AssemblyName>Getf.Service.Transfer</AssemblyName> <AssemblyName>Getf.Service.Transfer</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion> <TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic> <Deterministic>true</Deterministic>
<PublishUrl>publish\</PublishUrl> <PublishUrl>publish\</PublishUrl>
@@ -26,6 +26,7 @@
<IsWebBootstrapper>false</IsWebBootstrapper> <IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust> <UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled> <BootstrapperEnabled>true</BootstrapperEnabled>
<TargetFrameworkProfile />
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget> <PlatformTarget>AnyCPU</PlatformTarget>
@@ -36,6 +37,7 @@
<DefineConstants>DEBUG;TRACE</DefineConstants> <DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget> <PlatformTarget>AnyCPU</PlatformTarget>
@@ -45,6 +47,7 @@
<DefineConstants>TRACE</DefineConstants> <DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="log4net, Version=1.2.13.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL"> <Reference Include="log4net, Version=1.2.13.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">

View File

@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<packages> <packages>
<package id="log4net" version="2.0.3" targetFramework="net40" /> <package id="log4net" version="2.0.3" targetFramework="net40" />
<package id="SuperSocket" version="1.6.6.1" targetFramework="net40" /> <package id="SuperSocket" version="1.6.6.1" targetFramework="net40" requireReinstallation="true" />
<package id="SuperSocket.Engine" version="1.6.6.1" targetFramework="net40" /> <package id="SuperSocket.Engine" version="1.6.6.1" targetFramework="net40" requireReinstallation="true" />
</packages> </packages>