gpt4 book ai didi

c# - 如何使用 HTTPclient 内容类型进行 POST = application/x-www-form-urlencoded

转载 作者:IT王子 更新时间:2023-10-29 03:44:25 32 4
gpt4 key购买 nike

我目前正在开发一个 wp8.1 应用程序 C#,我已经通过从 textbox.texts 创建一个 json 对象 (bm) 设法在 json 中对我的 api 执行一个 POST 方法。下面是我的代码。我如何使用相同的 textbox.text 并将它们作为 content type = application/x-www-form-urlencoded 发布。代码是什么?

Profile bm = new Profile();
bm.first_name = Names.Text;
bm.surname = surname.Text;

string json = JsonConvert.SerializeObject(bm);

MessageDialog messageDialog = new MessageDialog(json);//Text should not be empty
await messageDialog.ShowAsync();

HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");

byte[] messageBytes = Encoding.UTF8.GetBytes(json);
var content = new ByteArrayContent(messageBytes);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = client.PostAsync("myapiurl", content).Result;

最佳答案

var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("Input1", "TEST2"));
nvc.Add(new KeyValuePair<string, string>("Input2", "TEST2"));
var client = new HttpClient();
var req = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(nvc) };
var res = await client.SendAsync(req);

或者

var dict = new Dictionary<string, string>();
dict.Add("Input1", "TEST2");
dict.Add("Input2", "TEST2");
var client = new HttpClient();
var req = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(dict) };
var res = await client.SendAsync(req);

关于c# - 如何使用 HTTPclient 内容类型进行 POST = application/x-www-form-urlencoded,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43158250/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com