HttpClient post call 适用于邮递员,但不适用于 C#

Posted

技术标签:

【中文标题】HttpClient post call 适用于邮递员,但不适用于 C#【英文标题】:HttpClient post call works on postman but not C# 【发布时间】:2020-10-25 04:49:23 【问题描述】:

正如标题所说,我的 post-call 可以在 postman 中工作,但不能在 c# 中工作。无论我尝试什么,它都无法在我的 c# 代码中运行。

这是我的代码:

internal async Task<(string, int)> GetJsonFileFromApiCall(string query)
    
        var _client = new HttpClient();
        var apiUrl = "https://wf19vv0nsf-dsn.algolia.net/1/indexes/*/queries?x-algolia-agent=Algolia%20for%20vanilla%20javascript%20(lite)%203.27.0%3Binstantsearch.js%202.10.2%3BMagento2%20integration%20(1.12.1)%3BJS%20Helper%202.26.0&x-algolia-application-id=WF19VV0NSF&x-algolia-api-key=MDdmNjA0Mjc1YzRkZjI4MWMwZmQyMDI4MDc5NDY4ZjlkYzJmOTVmMWY5Yjc3MGFkNDRiODA4YjU0MDVlM2Q1YnRhZ0ZpbHRlcnM9";
        var load = new  Requests = new  IndexName = "magento2_tcg_productiondefault_products", Params = $"query=query&hitsPerPage=12&maxValuesPerFacet=8&page=0&highlightPreTag=__ais-highlight__&highlightPostTag=__%2Fais-highlight__&ruleContexts=%5B%22magento_filters%22%2C%22%22%5D&facets=%5B%22mtg_setcode%22%2C%22is_foil%22%2C%22mtg_rarity%22%2C%22sf_colours%22%2C%22sf_types%22%2C%22sf_legalities%22%2C%22price.AUD.default%22%2C%22stock_qty%22%2C%22mtg_cmc%22%5D&numericFilters=%5B%22visibility_search%3D1%22%5D"  ;

        var message = await _client.PostAsync(apiUrl, GetStringContent(load));
        message.EnsureSuccessStatusCode();
        
        var jToken = JObject.Parse(await message.Content.ReadAsStringAsync());
        
        //temp return
        return ("", 1);
     

    private static StringContent GetStringContent<T>(T load)
    
        var serializeObject = JsonConvert.SerializeObject(load, new JsonSerializerSettings  ContractResolver = new CamelCasePropertyNamesContractResolver() );
        return new StringContent(serializeObject, Encoding.UTF8, "application/json");
    

这是我的邮递员截图:

需要注意的一点是,post 请求在进行 post 调用时会接收表单数据。

【问题讨论】:

httpclient 代码在哪里? headers 设置在哪里? ***.com/help/minimal-reproducible-example 我已经添加了 httpclient 代码。我不太清楚标题设置是什么意思(对此有点新) 对于那些试图帮助你的人来说,“不起作用”也不是很具描述性。 目前的反应是什么?你有例外吗?你得到一个空的回应?我认为该错误是由 URI 的格式化方式引起的。您可能需要使用 HttpUtility.UrlEncode() 来更好地格式化您的 URI 有错误吗? 【参考方案1】:

我认为你应该更改这行代码

var load = new  Requests = new  IndexName = "magento2_tcg_productiondefault_products", Params = $"query=query&hitsPerPage=12&maxValuesPerFacet=8&page=0&highlightPreTag=__ais-highlight__&highlightPostTag=__%2Fais-highlight__&ruleContexts=%5B%22magento_filters%22%2C%22%22%5D&facets=%5B%22mtg_setcode%22%2C%22is_foil%22%2C%22mtg_rarity%22%2C%22sf_colours%22%2C%22sf_types%22%2C%22sf_legalities%22%2C%22price.AUD.default%22%2C%22stock_qty%22%2C%22mtg_cmc%22%5D&numericFilters=%5B%22visibility_search%3D1%22%5D"  ;

到这里:

var load = new  Requests = new[] new   IndexName = "magento2_tcg_productiondefault_products", Params = $"query=query&hitsPerPage=12&maxValuesPerFacet=8&page=0&highlightPreTag=__ais-highlight__&highlightPostTag=__%2Fais-highlight__&ruleContexts=%5B%22magento_filters%22%2C%22%22%5D&facets=%5B%22mtg_setcode%22%2C%22is_foil%22%2C%22mtg_rarity%22%2C%22sf_colours%22%2C%22sf_types%22%2C%22sf_legalities%22%2C%22price.AUD.default%22%2C%22stock_qty%22%2C%22mtg_cmc%22%5D&numericFilters=%5B%22visibility_search%3D1%22%5D"  ;

【讨论】:

抱歉回复晚了,这对您有帮助!【参考方案2】:

在您的邮递员请求中,您的 post-body 的 requests 属性是一个数组


  "requests": [...]

而在您的 C# 代码中,它是一个对象

var load = new  
  Requests = new  ...  

因此服务器可能无法从您的请求中获取所需的数据。将requests 属性创建为List&lt;object&gt;object[],以便将其序列化为数组

var load = new 
  Requests = new List<object>new ...

【讨论】:

感谢您的解释,这很有帮助!【参考方案3】:

请参阅下面代码中的注释也包括错误..

internal async Task<(string, int)> GetJsonFileFromApiCall(string query)

    var _client = new HttpClient();
    var apiUrl = "https://wf19vv0nsf-dsn.algolia.net/1/indexes/*/queries?x-algolia-agent=Algolia%20for%20vanilla%20JavaScript%20(lite)%203.27.0%3Binstantsearch.js%202.10.2%3BMagento2%20integration%20(1.12.1)%3BJS%20Helper%202.26.0&x-algolia-application-id=WF19VV0NSF&x-algolia-api-key=MDdmNjA0Mjc1YzRkZjI4MWMwZmQyMDI4MDc5NDY4ZjlkYzJmOTVmMWY5Yjc3MGFkNDRiODA4YjU0MDVlM2Q1YnRhZ0ZpbHRlcnM9";
    
    var load = new 
     
        Requests = new 
         
            IndexName = "magento2_tcg_productiondefault_products", 
            
            Params = $"query=query&hitsPerPage=12&maxValuesPerFacet=8&page=0&highlightPreTag=__ais-highlight__&highlightPostTag=__
                        %2Fais-highlight__&ruleContexts=%5B%22magento_filters%22%2C%22%22%5D&facets=%5B%22mtg_setcode%22%2C%22is_foil%22%2C%22mtg_
                        rarity%22%2C%22sf_colours%22%2C%22sf_types%22%2C%22sf_legalities%22%2C%22price.AUD
                        .default%22%2C%22stock_qty%22%2C%22mtg_cmc%22%5D&numericFilters=%5B%22visibility_search%3D1%22%5D" 
         
    ;

    //insepct this..... im sure this is probably not what you think it is.
    //worth double checking
    var resultS = GetStringContent(load); //inspect the result value.

    var message = await _client.PostAsync(apiUrl, resultS);
    message.EnsureSuccessStatusCode();
    
    var jToken = JObject.Parse(await message.Content.ReadAsStringAsync());
    
    //temp return
    return ("", 1);
 

private static StringContent GetStringContent<T>(T load)

    var serializeObject = JsonConvert.SerializeObject(load, new JsonSerializerSettings  ContractResolver = new CamelCasePropertyNamesContractResolver() );
    return new StringContent(serializeObject, Encoding.UTF8, "application/json");

【讨论】:

以上是关于HttpClient post call 适用于邮递员,但不适用于 C#的主要内容,如果未能解决你的问题,请参考以下文章

关于httpclient 请求https (如何绕过证书验证)

取消 'HttpClient' POST 请求

.Net(C#)后台发送Get和Post请求的几种方法总结

httpclient post

Posting with HttpClient

我终于放弃HttpClient,选择这个牛逼的神仙工具!贼爽!