大部分HTTP库都是支持直接设置多表单字段的,但UE4的HttpRequest比较惨,只能用SetContent设置整个的TArray<uint8>作为请求体,所以想要传多表单就要自己拼。
首先设置Header,Content-Type设置为多表单,并设置boundary:
cpp
auto HttpRequest = FHttpModule::Get().CreateRequest();
HttpRequest->SetHeader("Content-Type", TEXT("multipart/form-data; boundary=yourboundary"));
HttpRequest->SetURL(yourUrl);
HttpRequest->SetVerb("POST");
boundary想设什么都行,但要和后面用的统一。
然后拼请求体的数据字段部分:
cpp
FString RequestBody;
FString Boundary = TEXT("--yourboundary\r\nContent-Disposition: form-data; name=");
//拼入单个属性
FString Field = Boundary + TEXT("\"") + Key + TEXT("\"\r\n\r\n") + Value + TEXT("\r\n");
RequestBody += Field;
这里需要注意,分隔两个属性的boundary行要比Header里设置的boundary前面多两个横杠
然后拼入文件:
cpp
RequestBody += TEXT("--yourboundary\r\nContent-Disposition: form-data; name=\"file\"; "); //分隔行和前缀
RequestBody += TEXT("filename=\"") + FileName + TEXT("\"\r\n\r\n"); //文件名
RequestBody += FString::FromBlob(Buffer.GetData(), Buffer.Num()); //文件
RequestBody += TEXT("\r\n--yourboundary--\r\n"); //结尾分隔行
结尾分隔行最后要有两个横杠。
然后把请求体设置进去,就可以传了:
cpp
HttpRequest->SetContentAsString(RequestBody);
HttpRequest->OnProcessRequestComplete().BindLambda([](FHttpRequestPtr Request, FHttpResponsePtr Response, bool bSuccess)
{
if (Response.IsValid())
{
FString ResponseStr = Response->GetContentAsString();
UE_LOG(LogTemp, Warning, TEXT("Upload Response: %s"), *ResponseStr);
}
else
{
UE_LOG(LogTemp, Error, TEXT("Upload failed"));
}
});
HttpRequest->ProcessRequest();