完善AxiHttp

This commit is contained in:
sin365 2025-09-22 14:07:05 +08:00
parent a2d57fee0e
commit 07d53bb916
3 changed files with 112 additions and 228 deletions

View File

@ -1,4 +1,5 @@
using System; using System;
using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO.Compression; using System.IO.Compression;
@ -11,7 +12,7 @@ using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading; using System.Threading;
public static class PSVThread public static class AxiHttpThread
{ {
#if UNITY_PSP2 #if UNITY_PSP2
@ -85,7 +86,7 @@ public static class AxiHttp
public const string Transfer_Encoding = "transfer-encoding"; public const string Transfer_Encoding = "transfer-encoding";
public const string Connection = "connection"; public const string Connection = "connection";
public static long index = 0; public static long index = 0;
static int singlePkgMaxRead = 1024; static int singlePkgMaxRead = 1024 * 4;
public class WaitAxiRequest : UnityEngine.CustomYieldInstruction public class WaitAxiRequest : UnityEngine.CustomYieldInstruction
{ {
@ -110,7 +111,13 @@ public static class AxiHttp
//Console.WriteLine(log); //Console.WriteLine(log);
} }
static Dictionary<string, IPAddress> dictIP2Address = new Dictionary<string, IPAddress>(); static ConcurrentDictionary<string, IPAddress> dictIP2Address = new ConcurrentDictionary<string, IPAddress>();
public enum AxiDownLoadMode
{
NotDownLoad = 0,
DownLoadBytes = 1,
DownloadToBinaryWriter = 2
}
public class AxiRespInfo public class AxiRespInfo
{ {
@ -120,78 +127,58 @@ public static class AxiHttp
{ {
get get
{ {
return return isDone == true && (code != 200 || !string.IsNullOrEmpty(errInfo));
isDone = true
&&
(
!string.IsNullOrEmpty(ErrInfo)
||
code != 200
);
} }
} }
public string ErrInfo; public string errInfo;
//public string Err = null; public string host = string.Empty;//host主机头
public string host = "";//host主机头 public string url = string.Empty;//pathAndQuery
public string url = "";//pathAndQuery public string requestRaw = string.Empty;
public int port = 80; public string encoding = string.Empty;
public string requestRaw = ""; public string header = string.Empty;
public string encoding = "";
public string header = "";
public string text { get { return body; } } public string text { get { return body; } }
public string body = ""; public string body = string.Empty;
public string reuqestBody = ""; public string reuqestBody = string.Empty;
public string reuqestHeader = ""; public string reuqestHeader = string.Empty;
public Dictionary<string, string> headers = new Dictionary<string, string>(); public Dictionary<string, string> headers = new Dictionary<string, string>();
public string response = ""; public bool isgzip = false;
//public string gzip = "";
public bool isGzip = false;
public int length = 0; public int length = 0;
public int code = 0; public int code = 0;
public int location = 0; public int runtime = 0;//获取网页消耗时间,毫秒
public int runTime = 0;//获取网页消耗时间,毫秒 public string cookies = string.Empty;
public int sleepTime = 0;//休息时间 public bool isTimeOut = false;
public string cookies = ""; public int needdownloadLenght;
public bool bTimeOut = false; public int loadedlenght;
public byte[] data { get { return bodyraw; } }
public int NeedloadedLenght; public byte[] bodyraw;
public int loadedLenght; public string filename;
public byte[] data { get { return bodyRaw; } } public float downLoadPr => needdownloadLenght <= 0 ? -1 : (float)loadedlenght / needdownloadLenght;
public byte[] bodyRaw; public void SetIsDone()
public string fileName; {
public float DownLoadPr => this.isDone = true;
NeedloadedLenght <= 0 ? -1 : (float)loadedLenght / NeedloadedLenght;
public System.IO.BinaryWriter binaryWriter;
} }
public void SetDoneForCantStart(int code, string errmsg)
public static IPAddress GetDnsIP(string str)
{ {
lock (dictIP2Address) this.code = code;
this.errInfo = errmsg;
this.isDone = true;
}
}
public static IPAddress GetDnsIP(string hostname)
{ {
if (!dictIP2Address.ContainsKey(str)) return dictIP2Address.GetOrAdd(hostname, key =>
{ {
IPHostEntry host = Dns.GetHostEntry(str); IPHostEntry host = Dns.GetHostEntry(hostname);
IPAddress ip = null;
foreach (var item in host.AddressList) foreach (var item in host.AddressList)
{ {
if (item.AddressFamily == AddressFamily.InterNetwork) if (item.AddressFamily == AddressFamily.InterNetwork)
{ {
ip = item; break; return item; ;
} }
} }
dictIP2Address[str] = ip; return null;
});
} }
return dictIP2Address[str];
}
}
public enum AxiDownLoadMode
{
NotDownLoad = 0,
DownLoadBytes = 1,
DownloadToBinaryWriter = 2
}
public static AxiRespInfo AxiRequest(string url) public static AxiRespInfo AxiRequest(string url)
{ {
AxiRespInfo respInfo = new AxiRespInfo(); AxiRespInfo respInfo = new AxiRespInfo();
@ -199,7 +186,6 @@ public static class AxiHttp
SendAxiRequest(url, ref respInfo); SendAxiRequest(url, ref respInfo);
return respInfo; return respInfo;
} }
public static WaitAxiRequest AxiRequestAsync(string url) public static WaitAxiRequest AxiRequestAsync(string url)
{ {
AxiRespInfo respInfo = new AxiRespInfo(); AxiRespInfo respInfo = new AxiRespInfo();
@ -207,10 +193,9 @@ public static class AxiHttp
WaitAxiRequest respAsync = new WaitAxiRequest(respInfo); WaitAxiRequest respAsync = new WaitAxiRequest(respInfo);
//Task task = new Task(() => SendAxiRequest(url, ref respInfo)); //Task task = new Task(() => SendAxiRequest(url, ref respInfo));
//task.Start() //task.Start()
PSVThread.DoTask(() => SendAxiRequest(url, ref respInfo)); AxiHttpThread.DoTask(() => SendAxiRequest(url, ref respInfo));
return respAsync; return respAsync;
} }
public static AxiRespInfo AxiDownload(string url) public static AxiRespInfo AxiDownload(string url)
{ {
AxiRespInfo respInfo = new AxiRespInfo(); AxiRespInfo respInfo = new AxiRespInfo();
@ -218,32 +203,27 @@ public static class AxiHttp
SendAxiRequest(url, ref respInfo); SendAxiRequest(url, ref respInfo);
return respInfo; return respInfo;
} }
public static AxiRespInfo AxiDownloadAsync(string url) public static AxiRespInfo AxiDownloadAsync(string url)
{ {
AxiRespInfo respInfo = new AxiRespInfo(); AxiRespInfo respInfo = new AxiRespInfo();
respInfo.downloadMode = AxiDownLoadMode.DownLoadBytes; respInfo.downloadMode = AxiDownLoadMode.DownLoadBytes;
//Task task = new Task(() => SendAxiRequest(url, ref respInfo)); AxiHttpThread.DoTask(() => SendAxiRequest(url, ref respInfo));
//task.Start();
PSVThread.DoTask(() => SendAxiRequest(url, ref respInfo));
return respInfo; return respInfo;
} }
static void SendAxiRequest(string url, ref AxiRespInfo respinfo, int timeout = 1000 * 1000, string encoding = "UTF-8") static void SendAxiRequest(string url, ref AxiRespInfo respinfo, int timeout = 1000 * 1000, string encoding = "UTF-8")
{ {
if (url.ToLower().StartsWith("https://")) if (url.ToLower().StartsWith("https://"))
SendAxiRequestHttps(url, ref respinfo, timeout, encoding);// SendAxiRequestHttps(url, ref respinfo, timeout, encoding); SendAxiRequestHttps(url, ref respinfo, timeout, encoding);
else else
SendAxiRequestHttp(url, ref respinfo, timeout, encoding); SendAxiRequestHttp(url, ref respinfo, timeout, encoding);
} }
static void SendAxiRequestHttp(string url, ref AxiRespInfo respinfo, int timeout, string encoding) static void SendAxiRequestHttp(string url, ref AxiRespInfo respinfo, int timeout, string encoding)
{ {
Log("SendAxiRequestHttp"); Log("SendAxiRequestHttp");
respinfo.url = url; respinfo.url = url;
Stopwatch sw = new Stopwatch(); Stopwatch sw = new Stopwatch();
sw.Start(); sw.Start();
respinfo.loadedLenght = 0; respinfo.loadedlenght = 0;
try try
{ {
string strURI = url; string strURI = url;
@ -258,14 +238,10 @@ public static class AxiHttp
if (!ParseURI(strURI, ref bSSL, ref strHost, ref strIP, ref port, ref strRelativePath, ref ourErrMsg)) if (!ParseURI(strURI, ref bSSL, ref strHost, ref strIP, ref port, ref strRelativePath, ref ourErrMsg))
{ {
Log("ParseURI False"); Log("ParseURI False");
respinfo.ErrInfo = ourErrMsg; respinfo.SetDoneForCantStart(0, "Can not Connect");
respinfo.code = 0;
respinfo.isDone = true;
return; return;
} }
var ip = GetDnsIP(strHost); var ip = GetDnsIP(strHost);
var ipEndPoint = new IPEndPoint(ip, port); var ipEndPoint = new IPEndPoint(ip, port);
@ -277,12 +253,10 @@ public static class AxiHttp
{ {
client.Close(); client.Close();
sw.Stop(); sw.Stop();
respinfo.code = 0; respinfo.SetDoneForCantStart(0, "Can not Connect");
respinfo.isDone = true;
return; return;
} }
//string requestRaw = $"GET {strRelativePath} HTTP/1.1\r\nHost: {strHost}\r\nConnection: Close\r\n\r\n";
string request = $"GET {strURI} HTTP/1.1\r\nHost: {strHost}\r\nConnection: Close\r\n\r\n"; string request = $"GET {strURI} HTTP/1.1\r\nHost: {strHost}\r\nConnection: Close\r\n\r\n";
checkContentLength(ref respinfo, ref request); checkContentLength(ref respinfo, ref request);
@ -312,7 +286,6 @@ public static class AxiHttp
&& sw.ElapsedMilliseconds < timeout && sw.ElapsedMilliseconds < timeout
); );
respinfo.header = sb.ToString().Replace(CTRL, ""); respinfo.header = sb.ToString().Replace(CTRL, "");
string[] headers = Regex.Split(respinfo.header, CT); string[] headers = Regex.Split(respinfo.header, CT);
if (headers != null && headers.Length > 0) if (headers != null && headers.Length > 0)
@ -343,7 +316,6 @@ public static class AxiHttp
location = Tools.getCurrentPath(url) + location; location = Tools.getCurrentPath(url) + location;
} }
rsb.Insert(urlStart, location); rsb.Insert(urlStart, location);
//return sendHTTPRequest(count, host, port, payload, rsb.ToString(), timeout, encoding, false);
client.Close(); client.Close();
sw.Stop(); sw.Stop();
SendAxiRequest(url, ref respinfo, timeout, encoding); SendAxiRequest(url, ref respinfo, timeout, encoding);
@ -356,33 +328,19 @@ public static class AxiHttp
{ {
Log("User Head"); Log("User Head");
int length = int.Parse(respinfo.headers[Content_Length]); int length = int.Parse(respinfo.headers[Content_Length]);
respinfo.NeedloadedLenght = length; respinfo.needdownloadLenght = length;
// while (respinfo.loadedLenght < length while (respinfo.loadedlenght < length
// && sw.ElapsedMilliseconds < timeout
// )
//{
// int readsize = length - respinfo.loadedLenght;
// len = client.Receive(temp_responseBody, respinfo.loadedLenght, readsize, SocketFlags.None);
// if (len > 0)
// {
// respinfo.loadedLenght += len;
// }
//}
while (respinfo.loadedLenght < length
&& sw.ElapsedMilliseconds < timeout && sw.ElapsedMilliseconds < timeout
) )
{ {
//len = client.Receive(temp_responseBody, respinfo.loadedLenght, readsize, SocketFlags.None); int readsize = length - respinfo.loadedlenght;
int readsize = length - respinfo.loadedLenght;
readsize = Math.Min(readsize, singlePkgMaxRead); readsize = Math.Min(readsize, singlePkgMaxRead);
len = client.Receive(temp_responseBody, 0, readsize, SocketFlags.None); len = client.Receive(temp_responseBody, 0, readsize, SocketFlags.None);
if (len > 0) if (len > 0)
{ {
memoryStream.Write(temp_responseBody, 0, len); memoryStream.Write(temp_responseBody, 0, len);
respinfo.loadedLenght += len; respinfo.loadedlenght += len;
} }
} }
} }
@ -394,7 +352,7 @@ public static class AxiHttp
int chunkedSize = 0; int chunkedSize = 0;
byte[] chunkedByte = new byte[1]; byte[] chunkedByte = new byte[1];
//读取总长度 //读取总长度
respinfo.loadedLenght = 0; respinfo.loadedlenght = 0;
do do
{ {
string ctmp = ""; string ctmp = "";
@ -418,27 +376,12 @@ public static class AxiHttp
//结束了 //结束了
break; break;
} }
//int onechunkLen = 0;
//while (onechunkLen < chunkedSize
// && sw.ElapsedMilliseconds < timeout
// )
//{
// len = client.Receive(responseBody, respinfo.loadedLenght, chunkedSize - onechunkLen, SocketFlags.None);
// if (len > 0)
// {
// onechunkLen += len;
// respinfo.loadedLenght += len;
// }
//}
int onechunkLen = 0; int onechunkLen = 0;
while (onechunkLen < chunkedSize while (onechunkLen < chunkedSize
&& sw.ElapsedMilliseconds < timeout && sw.ElapsedMilliseconds < timeout
) )
{ {
//len = client.Receive(responseBody, respinfo.loadedLenght, chunkedSize - onechunkLen, SocketFlags.None);
int readsize = chunkedSize - onechunkLen; int readsize = chunkedSize - onechunkLen;
readsize = Math.Min(readsize, singlePkgMaxRead); readsize = Math.Min(readsize, singlePkgMaxRead);
len = client.Receive(temp_responseBody, 0, readsize, SocketFlags.None); len = client.Receive(temp_responseBody, 0, readsize, SocketFlags.None);
@ -446,7 +389,7 @@ public static class AxiHttp
{ {
memoryStream.Write(temp_responseBody, 0, len); memoryStream.Write(temp_responseBody, 0, len);
onechunkLen += len; onechunkLen += len;
respinfo.loadedLenght += len; respinfo.loadedlenght += len;
} }
} }
@ -463,15 +406,14 @@ public static class AxiHttp
{ {
if (client.Available > 0) if (client.Available > 0)
{ {
//len = client.Receive(responseBody, respinfo.loadedLenght, (1024 * 200) - respinfo.loadedLenght, SocketFlags.None); int readsize = (1024 * 200) - respinfo.loadedlenght;
int readsize = (1024 * 200) - respinfo.loadedLenght;
readsize = Math.Min(readsize, singlePkgMaxRead); readsize = Math.Min(readsize, singlePkgMaxRead);
len = client.Receive(temp_responseBody, 0, readsize, SocketFlags.None); len = client.Receive(temp_responseBody, 0, readsize, SocketFlags.None);
if (len > 0) if (len > 0)
{ {
memoryStream.Write(temp_responseBody, 0, len); memoryStream.Write(temp_responseBody, 0, len);
respinfo.loadedLenght += len; respinfo.loadedlenght += len;
} }
} }
else else
@ -490,59 +432,52 @@ public static class AxiHttp
//判断是否gzip //判断是否gzip
if (respinfo.headers.ContainsKey(Content_Encoding)) if (respinfo.headers.ContainsKey(Content_Encoding))
{ {
respinfo.bodyRaw = unGzipBytes(responseBody, respinfo.loadedLenght); respinfo.bodyraw = unGzipBytes(responseBody, respinfo.loadedlenght);
} }
else else
{ {
respinfo.bodyRaw = responseBody; respinfo.bodyraw = responseBody;
} }
// 使用Uri类解析URL // 使用Uri类解析URL
Uri uri = new Uri(url); Uri uri = new Uri(url);
respinfo.fileName = System.IO.Path.GetFileName(uri.LocalPath); respinfo.filename = System.IO.Path.GetFileName(uri.LocalPath);
} }
else else
{ {
//判断是否gzip //判断是否gzip
if (respinfo.headers.ContainsKey(Content_Encoding)) if (respinfo.headers.ContainsKey(Content_Encoding))
{ {
respinfo.body = unGzip(responseBody, respinfo.loadedLenght, encod); respinfo.body = unGzip(responseBody, respinfo.loadedlenght, encod);
} }
else else
{ {
respinfo.body = encod.GetString(responseBody, 0, respinfo.loadedLenght); respinfo.body = encod.GetString(responseBody, 0, respinfo.loadedlenght);
} }
} }
client.Close(); client.Close();
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
respinfo.ErrInfo = $"ex : {ex.ToString()}"; respinfo.errInfo = $"ex : {ex.ToString()}";
} }
finally finally
{ {
sw.Stop(); sw.Stop();
respinfo.length = respinfo.loadedLenght; respinfo.length = respinfo.loadedlenght;
respinfo.runTime = (int)sw.ElapsedMilliseconds; respinfo.runtime = (int)sw.ElapsedMilliseconds;
respinfo.bTimeOut = sw.ElapsedMilliseconds >= timeout; respinfo.isTimeOut = sw.ElapsedMilliseconds >= timeout;
//if (socket != null)
//{
// clientSocket.Close();
//}
respinfo.isDone = true; respinfo.isDone = true;
} }
} }
static void SendAxiRequestHttps(string url, ref AxiRespInfo respinfo, int timeout, string encoding) static void SendAxiRequestHttps(string url, ref AxiRespInfo respinfo, int timeout, string encoding)
{ {
respinfo.url = url; respinfo.url = url;
Stopwatch sw = new Stopwatch(); Stopwatch sw = new Stopwatch();
sw.Start(); sw.Start();
respinfo.loadedLenght = 0; respinfo.loadedlenght = 0;
TcpClient client = null; TcpClient client = null;
try try
{ {
@ -558,34 +493,22 @@ public static class AxiHttp
if (!ParseURI(strURI, ref bSSL, ref strHost, ref strIP, ref port, ref strRelativePath, ref ourErrMsg)) if (!ParseURI(strURI, ref bSSL, ref strHost, ref strIP, ref port, ref strRelativePath, ref ourErrMsg))
{ {
Log("ParseURI False"); Log("ParseURI False");
respinfo.ErrInfo = ourErrMsg; respinfo.SetDoneForCantStart(0, ourErrMsg);
respinfo.code = 0;
respinfo.isDone = true;
return; return;
} }
//var ip = Dns.GetHostEntry(strHost).AddressList[0];
//var ipEndPoint = new IPEndPoint(ip, port);
//using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
//using (TcpClient tcpclient = new TcpClient())
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream()) using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
{ {
//client.Connect(ipEndPoint);
TimeOutSocket tos = new TimeOutSocket(); TimeOutSocket tos = new TimeOutSocket();
client = tos.Connect(strHost, port, timeout); client = tos.Connect(strHost, port, timeout);
if (!client.Connected) if (!client.Connected)
{ {
client.Close(); client.Close();
sw.Stop(); sw.Stop();
respinfo.code = 0; respinfo.SetDoneForCantStart(0, "");
respinfo.isDone = true;
return; return;
} }
SslStream ssl = null; SslStream ssl = null;
//string requestRaw = $"GET {strRelativePath} HTTP/1.1\r\nHost: {strHost}\r\nConnection: Close\r\n\r\n";
string request = $"GET {strURI} HTTP/1.1\r\nHost: {strHost}\r\nConnection: Close\r\n\r\n"; string request = $"GET {strURI} HTTP/1.1\r\nHost: {strHost}\r\nConnection: Close\r\n\r\n";
ssl = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate)); ssl = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate));
@ -599,15 +522,9 @@ public static class AxiHttp
ssl.Write(requestByte); ssl.Write(requestByte);
ssl.Flush(); ssl.Flush();
} }
checkContentLength(ref respinfo, ref request); checkContentLength(ref respinfo, ref request);
respinfo.requestRaw = request; respinfo.requestRaw = request;
byte[] temp_responseBody = new byte[singlePkgMaxRead]; byte[] temp_responseBody = new byte[singlePkgMaxRead];
//byte[] buffer = Encoding.ASCII.GetBytes(requestRaw);
//client.Send(buffer);
string tmp = ""; string tmp = "";
int len = 0; int len = 0;
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
@ -626,8 +543,6 @@ public static class AxiHttp
} while (!tmp.Equals(CTRL) } while (!tmp.Equals(CTRL)
&& sw.ElapsedMilliseconds < timeout && sw.ElapsedMilliseconds < timeout
); );
respinfo.header = sb.ToString().Replace(CTRL, ""); respinfo.header = sb.ToString().Replace(CTRL, "");
string[] headers = Regex.Split(respinfo.header, CT); string[] headers = Regex.Split(respinfo.header, CT);
if (headers != null && headers.Length > 0) if (headers != null && headers.Length > 0)
@ -658,7 +573,6 @@ public static class AxiHttp
{ {
respinfo.requestRaw = respinfo.requestRaw.Replace(url, respinfo.headers["location"]); respinfo.requestRaw = respinfo.requestRaw.Replace(url, respinfo.headers["location"]);
} }
//return sendHTTPRequest(count, host, port, payload, rsb.ToString(), timeout, encoding, false);
client.Close(); client.Close();
sw.Stop(); sw.Stop();
SendAxiRequest(url, ref respinfo, timeout, encoding); SendAxiRequest(url, ref respinfo, timeout, encoding);
@ -671,17 +585,16 @@ public static class AxiHttp
{ {
Log("Use Head"); Log("Use Head");
int length = int.Parse(respinfo.headers[Content_Length]); int length = int.Parse(respinfo.headers[Content_Length]);
respinfo.NeedloadedLenght = length; respinfo.needdownloadLenght = length;
while (respinfo.loadedLenght < length && sw.ElapsedMilliseconds < timeout) while (respinfo.loadedlenght < length && sw.ElapsedMilliseconds < timeout)
{ {
//len = ssl.Read(responseBody, respinfo.loadedLenght, length - respinfo.loadedLenght); int readsize = length - respinfo.loadedlenght;
int readsize = length - respinfo.loadedLenght;
readsize = Math.Min(readsize, singlePkgMaxRead); readsize = Math.Min(readsize, singlePkgMaxRead);
len = ssl.Read(temp_responseBody, 0, readsize); len = ssl.Read(temp_responseBody, 0, readsize);
if (len > 0) if (len > 0)
{ {
memoryStream.Write(temp_responseBody, 0, len); memoryStream.Write(temp_responseBody, 0, len);
respinfo.loadedLenght += len; respinfo.loadedlenght += len;
} }
} }
} }
@ -693,7 +606,7 @@ public static class AxiHttp
int chunkedSize = 0; int chunkedSize = 0;
byte[] chunkedByte = new byte[1]; byte[] chunkedByte = new byte[1];
//读取总长度 //读取总长度
respinfo.loadedLenght = 0; respinfo.loadedlenght = 0;
do do
{ {
string ctmp = ""; string ctmp = "";
@ -728,7 +641,7 @@ public static class AxiHttp
{ {
memoryStream.Write(temp_responseBody, 0, len); memoryStream.Write(temp_responseBody, 0, len);
onechunkLen += len; onechunkLen += len;
respinfo.loadedLenght += len; respinfo.loadedlenght += len;
} }
} }
@ -748,13 +661,13 @@ public static class AxiHttp
if (client.Available > 0) if (client.Available > 0)
{ {
//len = ssl.Read(responseBody, respinfo.loadedLenght, (1024 * 200) - respinfo.loadedLenght); //len = ssl.Read(responseBody, respinfo.loadedLenght, (1024 * 200) - respinfo.loadedLenght);
int readsize = (1024 * 200) - respinfo.loadedLenght; int readsize = (1024 * 200) - respinfo.loadedlenght;
readsize = Math.Min(readsize, singlePkgMaxRead); readsize = Math.Min(readsize, singlePkgMaxRead);
len = ssl.Read(temp_responseBody, 0, readsize); len = ssl.Read(temp_responseBody, 0, readsize);
if (len > 0) if (len > 0)
{ {
memoryStream.Write(temp_responseBody, 0, len); memoryStream.Write(temp_responseBody, 0, len);
respinfo.loadedLenght += len; respinfo.loadedlenght += len;
} }
} }
else else
@ -771,29 +684,29 @@ public static class AxiHttp
if (respinfo.downloadMode > AxiDownLoadMode.NotDownLoad) if (respinfo.downloadMode > AxiDownLoadMode.NotDownLoad)
{ {
//判断是否gzip //判断是否gzip
if (respinfo.isGzip) if (respinfo.isgzip)
{ {
respinfo.bodyRaw = unGzipBytes(responseBody, respinfo.loadedLenght); respinfo.bodyraw = unGzipBytes(responseBody, respinfo.loadedlenght);
} }
else else
{ {
respinfo.bodyRaw = responseBody; respinfo.bodyraw = responseBody;
} }
// 使用Uri类解析URL // 使用Uri类解析URL
Uri uri = new Uri(url); Uri uri = new Uri(url);
respinfo.fileName = System.IO.Path.GetFileName(uri.LocalPath); respinfo.filename = System.IO.Path.GetFileName(uri.LocalPath);
} }
else else
{ {
//判断是否gzip //判断是否gzip
if (respinfo.isGzip) if (respinfo.isgzip)
{ {
respinfo.body = unGzip(responseBody, respinfo.loadedLenght, encod); respinfo.body = unGzip(responseBody, respinfo.loadedlenght, encod);
} }
else else
{ {
respinfo.body = encod.GetString(responseBody, 0, respinfo.loadedLenght); respinfo.body = encod.GetString(responseBody, 0, respinfo.loadedlenght);
} }
} }
@ -802,27 +715,21 @@ public static class AxiHttp
} }
catch (Exception ex) catch (Exception ex)
{ {
respinfo.ErrInfo = $"ex : {ex.ToString()}"; respinfo.errInfo = $"ex : {ex.ToString()}";
} }
finally finally
{ {
client?.Close(); client?.Close();
sw.Stop(); sw.Stop();
respinfo.length = respinfo.loadedLenght; respinfo.length = respinfo.loadedlenght;
respinfo.runTime = (int)sw.ElapsedMilliseconds; respinfo.runtime = (int)sw.ElapsedMilliseconds;
respinfo.bTimeOut = sw.ElapsedMilliseconds >= timeout; respinfo.isTimeOut = sw.ElapsedMilliseconds >= timeout;
//if (socket != null) respinfo.SetIsDone();
//{
// clientSocket.Close();
//}
respinfo.isDone = true;
} }
if (client != null) if (client != null)
client.Dispose(); client.Dispose();
} }
private static void doHeader(ref AxiRespInfo respinfo, ref string[] headers) private static void doHeader(ref AxiRespInfo respinfo, ref string[] headers)
{ {
@ -832,7 +739,7 @@ public static class AxiHttp
{ {
respinfo.code = Tools.convertToInt(headers[i].Split(' ')[1]); respinfo.code = Tools.convertToInt(headers[i].Split(' ')[1]);
if (respinfo.code != 200 && respinfo.code != 301 && respinfo.code != 302) if (respinfo.code != 200 && respinfo.code != 301 && respinfo.code != 302)
respinfo.ErrInfo = "code:" + respinfo.code; respinfo.errInfo = "code:" + respinfo.code;
} }
else else
{ {
@ -859,7 +766,7 @@ public static class AxiHttp
} }
} }
} }
respinfo.isGzip = respinfo.headers.ContainsKey(Content_Encoding); respinfo.isgzip = respinfo.headers.ContainsKey(Content_Encoding);
} }
} }
@ -903,7 +810,6 @@ public static class AxiHttp
return str; return str;
} }
public static byte[] unGzipBytes(byte[] data, int len) public static byte[] unGzipBytes(byte[] data, int len)
{ {
System.IO.MemoryStream ms = new System.IO.MemoryStream(data, 0, len); System.IO.MemoryStream ms = new System.IO.MemoryStream(data, 0, len);
@ -1016,16 +922,11 @@ public static class AxiHttp
string strRelativePathRet; string strRelativePathRet;
string strIPRet; string strIPRet;
/*string strProtocol = strURI.Substring(0, 7); // 修复URL协议检查逻辑
if (strProtocol != "http://" string lowerUri = strURI.ToLower();
|| if (!lowerUri.StartsWith("http://") && !lowerUri.StartsWith("https://"))
strProtocol != "https://")
return false;*/
if (!strURI.ToLower().StartsWith("http://") || strURI.ToLower().StartsWith("https://"))
return false; return false;
bIsSSL = lowerUri.StartsWith("https://");
bIsSSL = strURI.ToLower().StartsWith("https://");
string strLeft = strURI.Substring(7, strURI.Length - 7); string strLeft = strURI.Substring(7, strURI.Length - 7);
int nIndexPort = strLeft.IndexOf(':'); int nIndexPort = strLeft.IndexOf(':');
@ -1078,8 +979,6 @@ public static class AxiHttp
strRelativePath = UrlEncode(strRelativePathRet); strRelativePath = UrlEncode(strRelativePathRet);
return true; return true;
} }
public static string UrlEncode(string str) public static string UrlEncode(string str)
{ {
string sb = ""; string sb = "";
@ -1100,15 +999,12 @@ public static class AxiHttp
} }
return sb; return sb;
} }
class Tools class Tools
{ {
public static long currentMillis() public static long currentMillis()
{ {
return (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds; return (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
} }
/// <summary> /// <summary>
/// 将16进制转换成10进制 /// 将16进制转换成10进制
/// </summary> /// </summary>
@ -1143,8 +1039,6 @@ public static class AxiHttp
return ""; return "";
} }
} }
/// <summary> /// <summary>
/// 将字符串转换成数字错误返回0 /// 将字符串转换成数字错误返回0
/// </summary> /// </summary>
@ -1164,7 +1058,6 @@ public static class AxiHttp
return 0; return 0;
} }
} }
class TimeOutSocket class TimeOutSocket
{ {
@ -1178,16 +1071,9 @@ public static class AxiHttp
sw.Start(); sw.Start();
TimeoutObject.Reset(); TimeoutObject.Reset();
socketexception = null; socketexception = null;
TcpClient tcpclient = new TcpClient(); TcpClient tcpclient = new TcpClient();
//IPHostEntry hostinfo = Dns.GetHostEntry("emu.axibug.com");
//IPAddress[] aryIP = hostinfo.AddressList;
//host = aryIP[0].ToString();
Log($"BeginConnect {host}:{port} timeoutMSec=>{timeoutMSec}"); Log($"BeginConnect {host}:{port} timeoutMSec=>{timeoutMSec}");
tcpclient.BeginConnect(host, port, new AsyncCallback(CallBackMethod), tcpclient); tcpclient.BeginConnect(host, port, new AsyncCallback(CallBackMethod), tcpclient);
if (TimeoutObject.WaitOne(timeoutMSec, false)) if (TimeoutObject.WaitOne(timeoutMSec, false))
{ {
if (IsConnectionSuccessful) if (IsConnectionSuccessful)
@ -1232,5 +1118,4 @@ public static class AxiHttp
} }
} }
} }
} }

View File

@ -13,7 +13,6 @@ public static class AxiHttpProxy
return new SendDownLoadProxy(AxiDownloadAsync(url)); return new SendDownLoadProxy(AxiDownloadAsync(url));
} }
public class SendWebRequestProxy public class SendWebRequestProxy
{ {
public WaitAxiRequest SendWebRequest; public WaitAxiRequest SendWebRequest;
@ -52,7 +51,7 @@ public static class AxiHttpProxy
Debug.Log($"url =>{resp.url}"); Debug.Log($"url =>{resp.url}");
Debug.Log($"Raw =>{resp.requestRaw}"); Debug.Log($"Raw =>{resp.requestRaw}");
Debug.Log($"code =>{resp.code}"); Debug.Log($"code =>{resp.code}");
Debug.Log($"respInfo.bTimeOut =>{resp.bTimeOut}"); Debug.Log($"respInfo.bTimeOut =>{resp.isTimeOut}");
Debug.Log($""); Debug.Log($"");
Debug.Log($"==== response ===="); Debug.Log($"==== response ====");
Debug.Log($"==== header ===="); Debug.Log($"==== header ====");
@ -64,21 +63,21 @@ public static class AxiHttpProxy
Debug.Log($"==== body ===="); Debug.Log($"==== body ====");
Debug.Log($"body_text =>{resp.body}"); Debug.Log($"body_text =>{resp.body}");
Debug.Log($"body_text.Length =>{resp.body.Length}"); Debug.Log($"body_text.Length =>{resp.body.Length}");
Debug.Log($"bodyRaw.Length =>{resp.bodyRaw?.Length}"); Debug.Log($"bodyRaw.Length =>{resp.bodyraw?.Length}");
Debug.Log($""); Debug.Log($"");
Debug.Log($"==== download ===="); Debug.Log($"==== download ====");
Debug.Log($"downloadMode =>{resp.downloadMode}"); Debug.Log($"downloadMode =>{resp.downloadMode}");
Debug.Log($"respInfo.fileName =>{resp.fileName}"); Debug.Log($"respInfo.fileName =>{resp.filename}");
Debug.Log($"respInfo.NeedloadedLenght =>{resp.NeedloadedLenght}"); Debug.Log($"respInfo.NeedloadedLenght =>{resp.needdownloadLenght}");
Debug.Log($"respInfo.loadedLenght =>{resp.loadedLenght}"); Debug.Log($"respInfo.loadedLenght =>{resp.loadedlenght}");
if (resp.bHadErr) if (resp.bHadErr)
{ {
Debug.LogError($"code->{resp.code} err->{resp.ErrInfo} url->{resp.url}"); Debug.LogError($"code->{resp.code} err->{resp.errInfo} url->{resp.url}");
} }
#else #else
Debug.Log($"==== request url => { resp.url}"); Debug.Log($"==== request url => { resp.url}");
Debug.Log($"code =>{resp.code}"); Debug.Log($"code =>{resp.code}");
Debug.Log($"respInfo.bTimeOut =>{resp.bTimeOut}"); Debug.Log($"respInfo.bTimeOut =>{resp.isTimeOut}");
Debug.Log($"==== response ===="); Debug.Log($"==== response ====");
if (resp.downloadMode == AxiDownLoadMode.NotDownLoad) if (resp.downloadMode == AxiDownLoadMode.NotDownLoad)
{ {
@ -88,7 +87,7 @@ public static class AxiHttpProxy
else else
{ {
Debug.Log($"==== download ===="); Debug.Log($"==== download ====");
Debug.Log($"respInfo.loadedLenght =>{resp.loadedLenght}"); Debug.Log($"respInfo.loadedLenght =>{resp.loadedlenght}");
} }
#endif #endif

View File

@ -29,7 +29,7 @@ public class AxiHttpTest : MonoBehaviour
while (!request.downloadHandler.isDone) while (!request.downloadHandler.isDone)
{ {
Debug.Log($"下载进度:{request.downloadHandler.DownLoadPr} ->{request.downloadHandler.loadedLenght}/{request.downloadHandler.NeedloadedLenght}"); Debug.Log($"下载进度:{request.downloadHandler.downLoadPr} ->{request.downloadHandler.loadedlenght}/{request.downloadHandler.needdownloadLenght}");
yield return null; yield return null;
} }
AxiHttpProxy.ShowAxiHttpDebugInfo(request.downloadHandler); AxiHttpProxy.ShowAxiHttpDebugInfo(request.downloadHandler);