Skip to content

Instantly share code, notes, and snippets.

@pedoc
Created September 24, 2024 07:57
Show Gist options
  • Save pedoc/cc319ee74e7989a7fd40a29000f21a77 to your computer and use it in GitHub Desktop.
Save pedoc/cc319ee74e7989a7fd40a29000f21a77 to your computer and use it in GitHub Desktop.
UrlEncode eq php and java
using System;
using System.Net;
using System.Text;
public class Program
{
public static void Main()
{
Console.WriteLine(PhpLikeUrlHelper.UrlEncode("Hello World! 你好 #$&\'()*+,-./:;=?@[]!\'", Encoding.UTF8));
}
}
public static class PhpLikeUrlHelper
{
public static string UrlEncode(string value, Encoding encoding)
{
if (string.IsNullOrEmpty(value))
return value;
StringBuilder encodedString = new StringBuilder();
foreach (char c in value)
{
if (c == ' ')
{
encodedString.Append('+'); // PHP/Java 将空格编码为 +
}
else if (IsSafe(c))
{
encodedString.Append(c);
}
else
{
// 对非 ASCII 字符进行 UTF-8 编码处理
byte[] bytes = encoding.GetBytes(c.ToString());
foreach (byte b in bytes)
{
encodedString.Append('%');
encodedString.Append(b.ToString("X2")); // 转换为十六进制
}
}
}
return encodedString.ToString();
}
private static bool IsSafe(char c)
{
// 允许的安全字符
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')
|| c == '-' || c == '_' || c == '.' || c == '~'; // 添加其他安全字符
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment