UE4 UriEncode 问题

时间:2021-12-28 07:25:18

类似JavaScript 的 encodeURI功能...

UE4使用IHttpRequest请求时 当Uri 路径中带中文字符时,需要进行百分比编码,否则无法正确解析Url路径和参数:

FString temp = FGenericPlatformHttp::UrlEncode(queryStr);
FString uri = FString::Printf(TEXT("http://www.yoursite.com?QueryString=%s"),*temp);

Note:

截至UE4.23,FGenericPlatformHttp::UrlEncode 函数不能解析整条http url.(因为UE4不会忽略’:‘,'/','@'以及'#' 等字符串)

如果需要整条字符串一起处理,可以考虑自己复制扩展或修改一下源码:

源码:

GenericPlatformHttp.cpp中修改AllowedChars 字符串 添加 ‘#’,‘/’,‘:’,'@'等符号进行忽略.

UE4 UriEncode 问题

或直接复制扩展,如:

static bool IsAllowedChar(UTF8CHAR LookupChar)
{
static char AllowedChars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-+=_.~:/#@?&";
static bool bTableFilled = false;
static bool AllowedTable[] = { false }; if (!bTableFilled)
{
for (int32 Idx = ; Idx < ARRAY_COUNT(AllowedChars) - ; ++Idx) // -1 to avoid trailing 0
{
uint8 AllowedCharIdx = static_cast<uint8>(AllowedChars[Idx]);
check(AllowedCharIdx < ARRAY_COUNT(AllowedTable));
AllowedTable[AllowedCharIdx] = true;
} bTableFilled = true;
} return AllowedTable[LookupChar];
} FString UCoreBPLibrary::UrlEncode( const FString &UnencodedString)
{
FTCHARToUTF8 Converter(*UnencodedString); //url encoding must be encoded over each utf-8 byte
const UTF8CHAR* UTF8Data = (UTF8CHAR*)Converter.Get(); //converter uses ANSI instead of UTF8CHAR - not sure why - but other code seems to just do this cast. In this case it really doesn't matter
FString EncodedString = TEXT(""); TCHAR Buffer[] = { , }; for (int32 ByteIdx = , Length = Converter.Length(); ByteIdx < Length; ++ByteIdx)
{
UTF8CHAR ByteToEncode = UTF8Data[ByteIdx]; if (IsAllowedChar(ByteToEncode))
{
Buffer[] = ByteToEncode;
FString TmpString = Buffer;
EncodedString += TmpString;
}
else if (ByteToEncode != '\0')
{
EncodedString += TEXT("%");
EncodedString += FString::Printf(TEXT("%.2X"), ByteToEncode);
}
}
return EncodedString;
}