如何使用C#在POST请求中发送JSON数据 [英] How to send json data in POST request using C#

查看:2002
本文介绍了如何使用C#在POST请求中发送JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用C#在POST请求中发送json数据.

I want to send json data in POST request using C#.

我尝试了几种方法,但是面临很多问题.我需要使用请求正文作为来自字符串的原始json和来自json文件的json数据进行请求.

I have tried few ways but facing lot of issues . I need to request using request body as raw json from string and json data from json file.

如何使用这两种数据形式发送请求.

How can i send request using these two data forms.

Ex:对于json中的身份验证请求正文-> {"Username":"myusername","Password":"pass"}

Ex: For authentication request body in json --> {"Username":"myusername","Password":"pass"}

对于其他API,请求主体应从外部json文件中检索.

For other APIs request body should retrieved from external json file.

推荐答案

您可以使用

You can use the HttpClient instead of the WebClient and HttpWebRequest. It's a newer implementation.

string myJson = "{'Username': 'myusername','Password':'pass'}";
using (var client = new HttpClient())
{
    var response = await client.PostAsync(
        "http://yourUrl", 
         new StringContent(myJson, Encoding.UTF8, "application/json"));
}

如果您需要更多HttpClient,则建议仅创建一个实例并重用它或使用新的HttpClientFactory.

When you need your HttpClient more then once it's recommended to only create one instance and reuse it or use the new HttpClientFactory.

这篇关于如何使用C#在POST请求中发送JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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