Delphi调用Shopify GraphQL Admin API遇406错误求助
解决Delphi调用Shopify GraphQL Admin API时的406 Not Acceptable错误
问题分析
406错误本质是服务器无法返回客户端Accept头指定的内容格式,但你用Postman能成功,说明Delphi的TRESTRequest组件发送的请求和Postman存在差异,核心问题集中在请求头的覆盖和JSON请求体的格式正确性上。
修复方案
1. 修正JSON请求体的转义方式
你当前手动拼接的JSON字符串用了HTML转义符",这会导致发送的JSON格式无效。Delphi中字符串的双引号需要用两个双引号转义,或者用TJSONObject构建请求体避免手动拼接错误。
2. 强制覆盖Accept请求头
TRESTRequest默认会自动追加多个Accept值(如text/html、application/xml等),而Shopify GraphQL API严格要求Accept为application/json,需通过组件的Accept属性直接设置,而非用AddParameter追加。
3. 明确请求体的Content-Type
添加请求体时指定ctAPPLICATION_JSON,确保请求体类型与头信息匹配,避免组件自动推断出错。
修复后完整代码
procedure TestShopify; var Client: TRESTClient; Request: TRESTRequest; Response: TRESTResponse; QueryObj: TJSONObject; begin Client := TRESTClient.Create('https://<my shop>.myshopify.com/admin/api/2025-10/graphql.json'); try Request := TRESTRequest.Create(Client); try Response := TRESTResponse.Create(Request); try Request.Response := Response; Request.Method := rmPOST; // 添加Shopify认证头 Request.AddParameter('X-Shopify-Access-Token', '<app token from shopify>', pkHTTPHEADER); // 强制设置Accept头,覆盖组件默认值 Request.Accept := 'application/json'; // 设置请求的Content-Type Request.ContentType := 'application/json'; // 使用TJSONObject构建请求体,避免手动转义错误 QueryObj := TJSONObject.Create; try QueryObj.AddPair('query', '{ shop { name myshopifyDomain } }'); Request.Body.ClearBody; Request.AddBody(QueryObj, ctAPPLICATION_JSON); finally QueryObj.Free; end; Request.Execute; // 输出响应内容验证结果 ShowMessage(Response.Content); finally Response.Free; end; finally Request.Free; end; finally Client.Free; end; end;
额外验证建议
- 可以用抓包工具(如Fiddler)对比Delphi和Postman发送的请求头,确认
Accept和Content-Type是否完全一致; - 如果仍有问题,检查Shopify的API版本是否兼容,确认令牌权限是否包含
read_shop权限。
内容的提问来源于stack exchange,提问作者Benjamin Keresztes
相关产品推荐
相关产品推荐

