Files
crtr/Assets/Cryville/Common/Network/HttpClient.cs
2022-09-30 17:32:21 +08:00

143 lines
4.3 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using Microsoft.Win32;
namespace Cryville.Common.Network {
public class HttpClient {
private readonly string _directHost;
protected string DirectHost { get { return _directHost; } }
private readonly int _directPort;
protected int DirectPort { get { return _directPort; } }
readonly Uri _baseUri;
readonly int origPort;
protected string Version = "HTTP/1.1";
protected TcpClient TcpClient;
protected virtual Stream Stream {
get {
return TcpClient.GetStream();
}
}
private readonly bool _proxied = false;
public Dictionary<string, string> Headers { get; set; }
public HttpClient(Uri baseUri, int port = 80) {
_directHost = baseUri.Host;
_directPort = port;
_baseUri = baseUri;
origPort = _baseUri.Port;
Headers = new Dictionary<string, string>();
_proxied = GetProxy(ref _directHost, ref _directPort);
Logger.Log("main", 0, "Network", "Connecting to {0}:{1}", DirectHost, DirectPort);
TcpClient = new TcpClient(DirectHost, DirectPort);
}
public virtual void Connect() {
if (_proxied) {
Request("CONNECT", _baseUri.Host + ":" + origPort.ToString());
}
}
public virtual void Close() {
TcpClient.Close();
}
public HttpResponse Request(string method, Uri uri, string body = null, Encoding encoding = null) {
string struri = GetUri(uri).PathAndQuery;
// if (_proxied) struri = GetUri(uri).AbsoluteUri;
return Request(method, struri, body, encoding);
}
public HttpResponse Request(string method, string uri, string body = null, Encoding encoding = null) {
var headers = new Dictionary<string, string>();
// if (Stream.CanTimeout) Stream.ReadTimeout = Stream.WriteTimeout = 5000;
foreach (var h in Headers)
headers.Add(h.Key, h.Value);
// headers["Accept"] = "text/plain, */*";
// headers["Connection"] = "close";
headers["Host"] = _baseUri.Host;
byte[] payload = new byte[0];
if (body != null) {
if (encoding == null)
encoding = Encoding.UTF8;
payload = encoding.GetBytes(body);
headers.Add("Content-Encoding", encoding.EncodingName);
headers.Add("Content-Length", payload.Length.ToString());
}
string request_line = string.Format(
"{0} {1} {2}\r\n", method, uri, Version
);
string header_fields = string.Concat((
from h in headers select h.Key + ":" + h.Value + "\r\n"
).ToArray());
byte[] buffer0 = Encoding.ASCII.GetBytes(string.Format(
"{0}{1}\r\n", request_line, header_fields
));
byte[] buffer1 = new byte[buffer0.Length + payload.Length];
Array.Copy(buffer0, buffer1, buffer0.Length);
Array.Copy(payload, 0, buffer1, buffer0.Length, payload.Length);
Logger.Log("main", 0, "Network", Encoding.UTF8.GetString(buffer1));
Stream.Write(buffer1, 0, buffer1.Length);
Stream.Flush();
var response = new HttpResponse(Stream);
Logger.Log("main", 0, "Network", "{0}", response);
return response;
}
protected virtual bool GetProxy(ref string host, ref int port) {
if (Environment.OSVersion.Platform == PlatformID.Win32NT) {
var reg = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings");
var proxyEnable = (int)reg.GetValue("ProxyEnable");
if (proxyEnable == 0) return false;
var proxyStr = (string)reg.GetValue("ProxyServer");
if (!string.IsNullOrEmpty(proxyStr)) {
string[] proxies = proxyStr.Split(';');
foreach (var p in proxies) {
if (p.StartsWith("http=")) {
string[] s = p.Split('=', ':');
host = s[1];
port = int.Parse(s[2]);
return true;
}
}
}
}
return false;
}
protected Uri GetUri(string path) {
Uri address;
if (_baseUri != null) {
if (!Uri.TryCreate(_baseUri, path, out address)) {
return new Uri(Path.GetFullPath(path));
}
}
else {
if (!Uri.TryCreate(path, UriKind.Absolute, out address)) {
return new Uri(Path.GetFullPath(path));
}
}
return GetUri(address);
}
protected Uri GetUri(Uri address) {
if (address == null) {
throw new ArgumentNullException("address");
}
Uri uri = address;
if (!address.IsAbsoluteUri && _baseUri != null && !Uri.TryCreate(_baseUri, address, out uri)) {
return address;
}
return uri;
}
}
}