如何从 Unreal Engine C++ 发送 GraphQL 请求?

How can I send a GraphQL request from Unreal Engine C++?

我成功发出了常规 HTTP 请求并收到了响应。现在我正尝试对 GraphQL 做同样的事情。 GraphQL 请求在 Postman 中返回 200 并带有预期的 JSON 主体,但是当我尝试在 C++ 中执行相同操作时,我收到 400 Bad Request。我的代码在下面,删除了访问令牌。

AApiClient::AApiClient()
 {
     //When the object is constructed, Get the HTTP module
     Http = &FHttpModule::Get();
 }
 
 void AApiClient::BeginPlay()
 {
     Super::BeginPlay();
     MyHttpCall();
 }
 
 void AApiClient::MyHttpCall()
 {
     TSharedRef<IHttpRequest, ESPMode::ThreadSafe> Request = Http->CreateRequest();
     Request->OnProcessRequestComplete().BindUObject(this, &AApiClient::OnResponseReceived);
     
     Request->SetURL("https://{my-access-token}@{my-url}.myshopify.com/admin/api/2021-04/graphql.json");
     Request->SetVerb("POST");
     Request->SetContentAsString("{\"query\": \"{ node(id: \"gid://shopify/Product/{my-product-id}\") { id ... on Product { title } } }\"}");
     Request->SetHeader(TEXT("User-Agent"), "X-UnrealEngine-Agent");
     Request->SetHeader("Content-Type", TEXT("application/json"));
 
     Request->ProcessRequest();
     UE_LOG(LogTemp, Warning, TEXT("Request sent."));
 }
 
 void AApiClient::OnResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
 {
     UE_LOG(LogTemp, Warning, TEXT("Response received"));
     UE_LOG(LogTemp, Warning, TEXT("The response code is {%i}"), Response->GetResponseCode());
     FString ResponseString = Response->GetContentAsString();
     UE_LOG(LogTemp, Warning, TEXT("The response is {%s}"), *ResponseString);
 }

我应该注意的一件事是,只有在我打开标有“禁用 cookie jar”的设置后,它才在 Postman 中起作用。我可能需要做一些类似于 C++ 中的事情,但还没有发现这是如何完成的。感谢任何帮助。

我让它工作了。我遇到的问题之一 运行 解释如下:

Shopify doesn't support cookies in POST requests that use basic HTTP authentication. Any POST requests that use basic authentication and include cookies will fail with a 200 error code.

从这里开始:https://shopify.dev/tutorials/authenticate-a-private-app-with-shopify-admin#generate-credentials-from-the-shopify-admin

这些是我所做的更改:

  1. 从 URL 中删除访问令牌。

Request->SetURL("https://{my-shop-url}.myshopify.com/admin/api/2021-04/graphql.json");

  1. 直接将 GraphQL 查询设置为内容而不删除空格(而不是像我上面的问题那样将查询作为 JSON 元素包含在内)。

Request->SetContentAsString("{ node(id: \"gid://shopify/Product/{my-product-id}\") { id ... on Product { title } }}");

  1. 更改内容类型 header 以使用 GraphQL。

Request->SetHeader("Content-Type", TEXT("application/graphql"));

  1. 添加应用密码作为访问令牌header。

Request->SetHeader("X-Shopify-Access-Token", TEXT("{my-app-password}"));

进行这些更改后,我收到了 200 OK 响应,其中包含我要查找的内容。