繁体   English   中英

如何从 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 不支持使用基本 HTTP 身份验证的 POST 请求中的 cookie。 任何使用基本身份验证并包含 cookie 的 POST 请求都将失败并显示 200 错误代码。

从这里: 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. 更改内容类型标头以使用 GraphQL。

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

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

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

进行这些更改后,我得到了 200 OK 响应,其中包含我正在寻找的内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM