C# HTTP POST JSON如何提交?

问题遇到的现象和发生背景

对方提供的接口要求提共的参数是JSON格式,C#如何提交POST类型的请示,总提示参数格式不对。

用代码块功能插入代码,请勿粘贴截图

重点是你要确定对方要求的编码格式,头部你要声明你发送的数据收是json,代码如下:关于json你使用Text.Json和Newtonsoft.Json来格式化都是可以的


using System.Text;

string appId = "xxxxx";
string appSecret = "xxxx";
string TYSHXYDM = "892374832718943A";
string param =  "{\"appId\":\"" + appId + "\",\"appSecret\":\"" + appSecret + "\",\"TYSHXYDM\":\"" + TYSHXYDM + "\"}";
string url = "https://xxxx.cn/api/v2/token/get";

var dict = new Dictionary<string, string>();
dict.Add("params", param);

using (var client = new HttpClient())
{
    var response = await client.PostAsync(
        url,
         new FormUrlEncodedContent(dict));
    var res = await response.Content.ReadAsStringAsync();
    Console.WriteLine(res);
}

参考一下 https://jingyan.baidu.com/article/bea41d4351579bf5c51be698.html

借鉴下面这段代码

public void GetResponse(string url, string json)
{

Encoding encoding = Encoding.UTF8;
byte[] data = encoding.GetBytes(json);
//此处为为http请求url
var uri = new Uri(url);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
//用此方法可以添加标准或非标准http请求,诸如conten-type ,accept,range等
request.Headers.Add("X-Auth-Token", System.Web.HttpUtility.UrlEncode("openstack"));
//此处为C#实现的一些标准http请求头添加方法,用上面的方面也可以实现
request.ContentType = "application/json";
request.Accept = "application/json";
// request.ContentLength = data.Length;
//此处添加标准http请求方面
request.Method = "POST";
System.IO.Stream sm = request.GetRequestStream();
sm.Write(data, 0, data.Length);
sm.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse, Encoding.UTF8);
Char[] readBuff = new Char[256];
int count = streamRead.Read(readBuff, 0, 256);
//content为http响应所返回的字符流
String content = "";
while (count > 0)
{
String outputData = new String(readBuff, 0, count);
content += outputData;
count = streamRead.Read(readBuff, 0, 256);
}
response.Close();
}



试下,修改了ContentType

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e) { }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string url = "xxx.cn/get";
        string param = "{\"appId\":\"aaaaaaaaaa\",\"appSecret\":\"bbbbbbbbbbbbbbbb\",\"TYSHXYDM\":\"cccccccccccccccccc\"}";
        var dict = new Dictionary();
        dict.Add("params", param);
        Response.Write(Post(url, dict));
    }
    public static string Post(string url, Dictionary dic)
    {
        string result = "";
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.Method = "POST";
        req.ContentType = "application/json";
        #region 添加Post 参数 
        StringBuilder builder = new StringBuilder();
        int i = 0;
        foreach (var item in dic) { if (i > 0) builder.Append("&"); builder.AppendFormat("{0}={1}", item.Key, item.Value); i++; }
        byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
        req.ContentLength = data.Length; using (Stream reqStream = req.GetRequestStream()) { reqStream.Write(data, 0, data.Length); reqStream.Close(); }
        #endregion
        HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
        Stream stream = resp.GetResponseStream(); //获取响应内容 
        using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { result = reader.ReadToEnd(); }
        return result;
    }
}

直接使用这个函数发消息


  public static void Post(string url, string param, Action<string> callback)
        {
            new Task(() =>
            {
                try
                {
                    //url https://10.10.2.41/artemis/api/xxxxx
                    //转换输入参数的编码类型,获取bytep[]数组 
                    byte[] byteArray = Encoding.UTF8.GetBytes(param);
                    //初始化新的webRequst
                    //1. 创建httpWebRequest对象
                    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
                    //2. 初始化HttpWebRequest对象
                    webRequest.Method = "POST";
                    webRequest.ContentType = "application/json;charset=UTF-8";
                    webRequest.ContentLength = byteArray.Length;
                    
                
                    //3. 附加要POST给服务器的数据到HttpWebRequest对象(附加POST数据的过程比较特殊,它并没有提供一个属性给用户存取,需要写入HttpWebRequest对象提供的一个stream里面。)
                    Stream newStream = webRequest.GetRequestStream();//创建一个Stream,赋值是写入HttpWebRequest对象提供的一个stream里面
                    newStream.Write(byteArray, 0, byteArray.Length);
                    newStream.Close();
                    //4. 读取服务器的返回信息
                    using (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse())
                    {
                        using (StreamReader stream = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                        {
                            string ret = stream.ReadToEnd();
                            callback(ret);
                        }
                    }
                }
                catch (Exception ex)
                {
                    callback("异常:" + ex.Message);
                }
            }).Start();
        }