如何使用HttpClient发布数据? [英] How to post data using HttpClient?

查看:24
本文介绍了如何使用HttpClient发布数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 this 来自 Nuget 的 HttpClient.

I have got this HttpClient from Nuget.

当我想获取数据时,我会这样做:

When I want to get data I do it this way:

var response = await httpClient.GetAsync(url);
var data = await response.Content.ReadAsStringAsync();

但问题是我不知道如何发布数据?我必须发送一个 post 请求并在其中发送这些值:comment="hello world"questionId = 1.这些可以是一个类的属性,我不知道.

But the problem is that I don't know how to post data? I have to send a post request and send these values inside it: comment="hello world" and questionId = 1. these can be a class's properties, I don't know.

更新我不知道如何将这些值添加到 HttpContent 因为 post 方法需要它.httClient.Post(string, HttpContent);

Update I don't know how to add those values to HttpContent as post method needs it. httClient.Post(string, HttpContent);

推荐答案

您需要使用:

await client.PostAsync(uri, content);

类似的东西:

var comment = "hello world";
var questionId = 1;

var formContent = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("comment", comment), 
    new KeyValuePair<string, string>("questionId", questionId) 
});

var myHttpClient = new HttpClient();
var response = await myHttpClient.PostAsync(uri.ToString(), formContent);

如果你需要在发布后得到回复,你应该使用:

And if you need to get the response after post, you should use:

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

希望有帮助;)

这篇关于如何使用HttpClient发布数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆