Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

c# - C#-POST请求中的正文内容(C# - Body content in POST request)

I need to make some api calls in C#.

(我需要在C#中进行一些api调用。)

I'm using Web API Client from Microsoft to do that.

(我正在使用Microsoft的Web API客户端来执行此操作。)

I success to make some POST requests, but I don't know how to add the field "Body" into my requests.

(我成功发出了一些POST请求,但是我不知道如何在请求中添加字段“ Body”。)

Any idea ?

(任何的想法 ?)

Here's my code:

(这是我的代码:)

    static HttpClient client = new HttpClient();
    public override void AwakeFromNib()
    {
        base.AwakeFromNib();
        notif_button.Activated += (sender, e) => {
        };
        tips_button.Activated += (sender, e) =>
        {
            Tip t1 = new Tip(title_tips.StringValue, pic_tips.StringValue, content_tips.StringValue, "TEST");
            client.BaseAddress = new Uri("my_url");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            CreateProductAsync(t1).Wait();
        };
    }

    static async Task<Uri> CreateProductAsync(Tip tips)
    {
        HttpResponseMessage response = await client.PostAsJsonAsync("api/add_tips", tips);
        response.EnsureSuccessStatusCode();
        return response.Headers.Location;
    }
  ask by Baptiste translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Step 1. Choose a type that derives from HttpContent .

(步骤1.选择从HttpContent派生的类型。)

If you want to write a lot of content with runtime code, you could use a StreamContent and open some sort of StreamWriter on it.

(如果要使用运行时代码编写大量内容,则可以使用StreamContent并在其上打开某种StreamWriter。)

For something short, use StringContent .

(对于简短内容,请使用StringContent 。)

You can also derive your own class for custom content.

(您还可以派生自己的类来定制内容。)

Step 2. Pass the content in a call to HttpClient.PostAsync .

(步骤2.将内容传递给HttpClient.PostAsync调用。)

Here's an example that uses StringContent to pass some JSON:

(这是一个使用StringContent传递一些JSON的示例:)

string json = JsonConvert.SerializeObject(someObject);
var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
var httpResponse = await httpClient.PostAsync("http://www.foo.bar", httpContent);

See also How do I set up HttpContent?

(另请参阅如何设置HttpContent?)

.

(。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...