HttpClient 发送 Post 请求 带 json 参数

预想代码: 本来想用 这个扩展的 泛型方法 的 PostAsJsonAsync  但是这个方法在 我的 类库中执行会报错:报错内容:

未能加载文件或程序集“”或它的某一个依赖。找到的程序集清单定义与程序集引用不匹配。

using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(Config.GetValue("unifiedPlatformIp"));
                    PushMsgModel postContent = new PushMsgModel() { access_token = access_token, uid = userId, title = title, content = content, alive = 10, param = new PubMsgType { type = "system" } };


                    var result = client.PostAsJsonAsync<PushMsgModel>("/hdl/uniwater/v1.0/app/message/push.json", postContent).Result;
                    string resultContent = result.Content.ReadAsStringAsync().Result;
                    return resultContent;
                }

最后代码: 我想既然是拓展方法 肯定只是为了后来方便 ,老方法应该也能满足这个功能,不然 以前 写 .net的人得多痛苦

using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(Config.GetValue("unifiedPlatformIp"));
                    PushMsgModel postContent = new PushMsgModel() { access_token = access_token, uid = userId, title = title, content = content, alive = 10, param = new PubMsgType { type = "system" } };

                    var result = client.PostAsync("/hdl/uniwater/v1.0/app/message/push.json",new StringContent( JsonConvert.SerializeObject(  postContent)) ).Result;
                    //var result = client.PostAsJsonAsync<PushMsgModel>("/hdl/uniwater/v1.0/app/message/push.json", postContent).Result;
                    string resultContent = result.Content.ReadAsStringAsync().Result;
                    return resultContent;
                }

查看了一下果不其然:

HttpClient异步Post请求,HttpClient.PostAsync(String, HttpContent, CancellationToken)

String为Post的Url,

HttpContent为发送到服务器的 HTTP 请求内容,就是Post过去的数据了。

HttpContent,常用的有   FormUrlEncodedContent、StringContent。

FormUrlEncodedContent是以KeyValuePair形式出现的,

假如你要传递的内容以KeyValue形式出现,可用。

但一般应用中我们都是将实体转成Json后传递的,谁还有哪个功夫一个个KeyValue对的写啊。

因此StringContent就是我经常使用的方法。

我直接把创建一个    new   StringContent (  "" )  当参数穿过去就完事了 ,就像我第二段代码写的

最后用的时候发现用   StringContent  不会被识别为  JSON 参数我日  ,参数根本不会被识别到,导致发送失败

得像上面这样 转 byte数组 再指定一下  请求头

猜你喜欢

转载自blog.csdn.net/qq_36445227/article/details/100568825