在C#后端代码的http get请求中包含原始文本

时间:2019-04-17 17:26:49

标签: c# .net http-post dotnet-httpclient

我有此代码:

 client.BaseAddress = new Uri("https://sandbox-quickbooks.api.intuit.com/v3/company/1232/vendor/70?minorversion=8");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Authorization
                         = new AuthenticationHeaderValue("Bearer", "bLpuw.vjbvIP_P7Vyj4ziSGa3Ohg");

            using (HttpResponseMessage response = client.PostAsync("https://sandbox-quickbooks.api.intuit.com/v3/company/1232/query?minorversion=8").Result)
            {
                using (HttpContent content = response.Content)
                {
                    var json = content.ReadAsStringAsync().Result;
                }
            }

根据quickbooks api Postman示例,它们在http post操作中包括原始文本查询。 示例:https://www.php.net/releases/

如何在c#发布请求中包含原始文本?

3 个答案:

答案 0 :(得分:0)

您需要像这样将内容传递给PostAsync方法

var myContent = "your string in here";
var buffer = System.Text.Encoding.UTF8.GetBytes(myContent);
var byteContent = new ByteArrayContent(buffer);

using (HttpResponseMessage response = client.PostAsync("https://sandbox-quickbooks.api.intuit.com/v3/company/1232/query?minorversion=8",bytecontent).Result)
            {
                using (HttpContent content = response.Content)
                {
                    var json = content.ReadAsStringAsync().Result;
                }
            }

答案 1 :(得分:0)

创建一个包含文本的StringContent()并将其传递给PostAsync()。

您可能需要检查所需的Content-Type标头,并将其也传递给StringContent构造函数。

例如

using (var requestContent = new StringContent(“any text”, Encoding.UTF8, “text/plain”))
{
      ... httpClient.PostAsync(url, requestContent)...
}

答案 2 :(得分:0)

client.BaseAddress = new Uri("https://sandbox-quickbooks.api.intuit.com/v3/company/1232/vendor/70?minorversion=8");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
    new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization
                = new AuthenticationHeaderValue("Bearer", "bLpuw.vjbvIP_P7Vyj4ziSGa3Ohg");

var postContent = new StringContent("myContent");

using (HttpResponseMessage response = client.PostAsync("https://sandbox-quickbooks.api.intuit.com/v3/company/1232/query?minorversion=8", postContent).Result)
{
    using (HttpContent content = response.Content)
    {
        var json = content.ReadAsStringAsync().Result;
    }
}

另外,请注意,您对Async方法的使用有误,应该始终等待而不是使用任务的Result属性。