我有一个我正在设置的HTTP游戏服务器,我有一个函数可以返回有关地图的大量信息。服务器的输出长约7800个字符,但是当我在游戏中获得URL的内容时,游戏只能获得1124个字符。
IHttpRequest的响应内容的长度是否有限制?
相关代码:
FString ANetwork::getContentsOfURL(FString URL, TArray<FString> keys, TArray<FString> values)
{
serverResponse = NULL;
TSharedRef<IHttpRequest> HttpRequest = FHttpModule::Get().CreateRequest();
HttpRequest->SetHeader(TEXT("Content-Type"), TEXT("application/json"));
int32 count = keys.Num();
URL += "?auth=" + authenticator;
for (int i = 0; i < count; i++)
{
URL += "&" + keys[i] + "=" + values[i];
}
HttpRequest->SetURL(URL);
HttpRequest->SetVerb(TEXT("GET"));
HttpRequest->OnProcessRequestComplete().BindUObject(this, &ANetwork::OnResponseReceived);
HttpRequest->ProcessRequest();
bool wait = true;
while (wait)
{
FHttpResponsePtr response = HttpRequest->GetResponse();
FHttpResponsePtr httpnull;
if (response != httpnull)
{
if (HttpRequest->GetResponse()->GetContentAsString() != "")
{
return HttpRequest->GetResponse()->GetContentAsString();
}
}
}
return "";
}
在旁注中,我不确定如何检查FHttpResponsePtr
是否指向空对象。我以为我在while循环中使用了该代码,但它似乎并没有产生影响。偶尔,代码会中断,因为当我尝试以字符串形式访问内容时,响应为空。
任何人都知道如何正确检查它是否为空?
Per @TheBrain的回答,这是我修改过的循环:
bool wait = true;
while (wait)
{
if (HttpRequest->GetStatus() != EHttpRequestStatus::Processing)
{
FHttpResponsePtr response = HttpRequest->GetResponse();
if (response.IsValid())
{
return response->GetContentAsString();
}
else
return "INVALID";
}
}
return "";
然而,这会导致无限循环。
答案 0 :(得分:2)
我不认为答案有这么小的限制。它看起来更像是在实际处理请求之前获取响应。只有在GetStatus()返回 Processing 之外的其他内容时,才应尝试调用GetResponse()。
在nullpointer检查:FHttpResponsePtr只是一个TSharedPtr。与任何TSharedPtr一样,您可以在指针本身上使用IsValid() 。例如,使用上面的代码:
FHttpResponsePtr response = HttpRequest->GetResponse();
if (response != nullptr) { // wrong, the pointer itself is never null!
if (response.IsValid()) { // correct, check for pointer validity
if (response.Get() != nullptr) { // basically the same, but longer
修改强>
很抱歉误会。你必须 从不 用这样的while循环阻止游戏循环。所以你有两种可能性:
以下是使用委托的工作代码示例:
void AYourActor::NetworkTest()
{
TSharedRef<IHttpRequest> HttpRequest = FHttpModule::Get().CreateRequest();
HttpRequest->SetHeader(TEXT("Content-Type"), TEXT("application/json"));
HttpRequest->SetURL("http://www.google.com");
HttpRequest->SetVerb(TEXT("GET"));
HttpRequest->OnProcessRequestComplete().BindUObject(this, &AYourActor::OnResponseReceived);
HttpRequest->ProcessRequest();
}
void AYourActor::OnResponseReceived(FHttpRequestPtr request, FHttpResponsePtr response, bool didConnect)
{
UE_LOG(LogExec, Warning, TEXT("Response received %d!"), didConnect);
UE_LOG(LogExec, Warning, TEXT("Response: %s"), *(response->GetContentAsString()));
}