C# CURL POST(内容类型,哈希键)

我目前正在尝试在 C# (API) 中发送 POST 请求,但是我在内容类型和授权方面遇到了一些麻烦,因为它的格式为 apiHash、apiKey。


卷曲示例:


curl -i -XPOST https://sandboxapi.g2a.com/v1/order \

-H "Authorization: qdaiciDiyMaTjxMt, 74026b3dc2c6db6a30a73e71cdb138b1e1b5eb7a97ced46689e2d28db1050875" \

-H 'Content-Type: application/json' \

-d '{"product_id": "10000027819004", "max_price": 45.0}'

API 文档:https : //www.g2a.com/integration-api/documentation/#api-Orders-AddOrder


这是我到目前为止的代码:


private static readonly HttpClient client = new HttpClient();


public async Task < string > makeRequest() {

    var values = new Dictionary < string,

        string > {

            {

                "product_id",

                "10000027819004"

            },

            {

                "max_price",

                "45.0"

            }

        };


    var content = new FormUrlEncodedContent(values);


    AuthenticationHeaderValue authHeaders = new AuthenticationHeaderValue("qdaiciDiyMaTjxMt", "74026b3dc2c6db6a30a73e71cdb138b1e1b5eb7a97ced46689e2d28db1050875");

    client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");


    client.DefaultRequestHeaders.Authorization = authHeaders;


    var response = await client.PostAsync("https://sandboxapi.g2a.com/v1/order", content);


    var responseString = await response.Content.ReadAsStringAsync();

    return responseString;

}

我尝试了多种解决方案,但似乎无法将它们全部正确(内容类型、授权和参数)。


冉冉说
浏览 338回答 2
2回答

qq_笑_17

您必须像这样设置内容类型:client.DefaultRequestHeaders &nbsp;&nbsp;.Accept &nbsp;&nbsp;.Add(new&nbsp;MediaTypeWithQualityHeaderValue("application/json"));这将解决问题。

慕容708150

您发送FormUrlEncodedContent的不是 JSON,而 curl 示例正在发送 JSON。重构您的方法以在StringContent具有正确内容类型集的情况下使用实际序列化的 JSON 字符串。public async Task<string> makeRequest() {&nbsp; &nbsp; var values = new {&nbsp; &nbsp; &nbsp; &nbsp; product_id = "10000027819004",&nbsp; &nbsp; &nbsp; &nbsp; max_price = 45.0&nbsp; &nbsp; };&nbsp; &nbsp; //-d '{"product_id": "10000027819004", "max_price": 45.0}'&nbsp; &nbsp; var json = JsonConvert.SerializeObject(values); //using Json.Net&nbsp; &nbsp; var content = new StringContent(json);&nbsp; &nbsp; var auth = "qdaiciDiyMaTjxMt, 74026b3dc2c6db6a30a73e71cdb138b1e1b5eb7a97ced46689e2d28db1050875";&nbsp; &nbsp; //-H "Authorization: qdaiciDiyMaTjxMt, 74026b3dc2c6db6a30a73e71cdb138b1e1b5eb7a97ced46689e2d28db1050875" \&nbsp; &nbsp; client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", auth);&nbsp; &nbsp; //-H 'Content-Type: application/json' \&nbsp; &nbsp; client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");&nbsp; &nbsp; var response = await client.PostAsync("https://sandboxapi.g2a.com/v1/order", content);&nbsp; &nbsp; var responseString = await response.Content.ReadAsStringAsync();&nbsp; &nbsp; return responseString;}
打开App,查看更多内容
随时随地看视频慕课网APP