使用HttpClient和WebRequest时POST一个对象的写法
【一】步骤:
1)将对象转化为Json字符串。
2)将Json字符串编码为byte数组。
3)设置传输对象(WebRequest或者HttpClient)的ContentType是"application/json"。
4)设置传输对象的ContentLength=Byte数组的长度。
5)开始传输
6)获取JSON结果:
【二】示例代码:
【对于WebRequest而言】

static void SendByWebRequesttoApi()
{
WebRequest req = WebRequest.Create("http://localhost:15203/api/ApiDefault");
var stu = new Student { ID = 1, Name = "董玮" };
string jsonString = JsonConvert.SerializeObject(stu);
byte[] objectContent = Encoding.UTF8.GetBytes(jsonString);
req.ContentLength = objectContent.Length;
req.ContentType = "application/json";
req.Method = "POST";
using (var stream = req.GetRequestStream())
{
stream.Write(objectContent, 0, objectContent.Length);
stream.Close();
} var resp = req.GetResponse();
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
string s = sr.ReadToEnd();
System.Console.WriteLine(s);
}
}

【对于HttpClient而言】

static void SendByHttpClienttoApi()
{
var stu = new { ID = 1, Name = "董玮" };
using (var client = new HttpClient())
{
string jsonString = JsonConvert.SerializeObject(stu);
byte[] bytes = Encoding.UTF8.GetBytes(jsonString);
using (StreamContent sc = new StreamContent(new MemoryStream(bytes)))
{
sc.Headers.ContentLength = bytes.Length;
sc.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
var result = client.PostAsync("http://localhost:15203/api/ApiDefault", sc).Result;
var objectResult = JsonConvert.DeserializeObject<Student>(result.Content.ReadAsStringAsync().Result);
} }
}

另外注意,以上是针对WebApi(WebApi默认是JSON格式数据传输)。如果是MVC的模式,那么默认是表单形式传输。因此:

static void SendByWebRequesttoMVC()
{
WebRequest req = WebRequest.Create("http://localhost:15203/Default/DoGetStudent");
var htmlFormPost = "ID=1&Name=董玮";
byte[] objectContent = Encoding.UTF8.GetBytes(htmlFormPost);
req.ContentLength = objectContent.Length;
req.ContentType = "application/x-www-form-urlencoded"; //必须写!
req.Method = "POST";
using (var stream = req.GetRequestStream())
{
stream.Write(objectContent, 0, objectContent.Length);
stream.Close();
} var resp = req.GetResponse();
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
string s = sr.ReadToEnd();
System.Console.WriteLine(s);
}
}

在HttpClient中,把StreamContent改为FormUrlEncodedContent,传入一个Dictionary<string,string>对象即可:

static void SendByHttpClienttoMVC()
{
using (var client = new HttpClient())
{
FormUrlEncodedContent fc = new FormUrlEncodedContent(new Dictionary<string, string>() { { "ID", "1" }, { "Name", "董玮" } });
var result = client.PostAsync("http://localhost:15203/Default/DoGetStudent", fc).Result;
System.Console.WriteLine(result.Content.ReadAsStringAsync().Result);
}
}

使用HttpClient和WebRequest时POST一个对象的写法的更多相关文章
- Makefile之写demo时的通用Makefile写法
Makefile之写demo时的通用Makefile写法[日期:2013-05-22] 来源:CSDN 作者:gqb666 [字体:大 中 小] 前面的一篇文章Makefile之大型工程项目子目录M ...
- HttpClient调用webApi时注意的小问题
HttpClient client = new HttpClient(); client.BaseAddress = new Uri(thisUrl); client.GetAsync("a ...
- httpclient访问网站时设置Accept-Encoding为gzip,deflate返回的结果为乱码的问题
近期迷恋上httpclient模拟各种网站登陆,浏览器中的开发者工具中查看请求头信息,然后照葫芦画瓢写到httpclient的请求中去,requestheader中有这么一段设置: Accept-En ...
- 使用httpclient抓取时,netstat 发现很多time_wait连接
http://wiki.apache.org/HttpComponents/FrequentlyAskedConnectionManagementQuestions 1. Connections in ...
- HttpClient 调用WebAPI时,传参的三种方式
public void Post() { //方法一,传json参数 var d = new { username = " ", password = " ", ...
- 实现在 .net 中使用 HttpClient 下载文件时显示进度
在 .net framework 中,要实现下载文件并显示进度的话,最简单的做法是使用 WebClient 类.订阅 DownloadProgressChanged 事件就行了. 但是很可惜,WebC ...
- Java中迭代列表中数据时几种循环写法的效率比较
Java中经常会用到迭代列表数据的情况,本文针对几种常用的写法进行效率比较.虽然网上已经有了类似的文章,但是对他们的结论并不认同. 常见的实现方法: 1.for循环: for(int i = 0; i ...
- mysql where 条件中的字段有NULL值时的sql语句写法
比如你有一个sql语句联表出来之后是这样的 id name phone status 1 张三 ...
- mybaties实体的 Mapper.xml文件中自定义sql时模糊查询的写法
<select id=selectByNameLike" parameterType="string" resultMap="BaseResultMap ...
随机推荐
- UVA - 11374 - Airport Express(堆优化Dijkstra)
Problem UVA - 11374 - Airport Express Time Limit: 1000 mSec Problem Description In a small city c ...
- 文本分类实战(三)—— charCNN模型
1 大纲概述 文本分类这个系列将会有十篇左右,包括基于word2vec预训练的文本分类,与及基于最新的预训练模型(ELMo,BERT等)的文本分类.总共有以下系列: word2vec预训练词向量 te ...
- AI MobileNet
MobileNet,是针对移动和嵌入式设备的一类高效模型,基于流线型(streamlined)架构,使用深度可分离卷积(depthwise separable convolution)来构建轻量级深度 ...
- Android测试(四):Instrumented 单元测试
原文:https://developer.android.com/training/testing/unit-testing/instrumented-unit-tests.html Instrume ...
- 1.[Andriod]之Andriod布局 VS WinPhone布局
0.写在前面的话 近来被HTML+CSS的布局折腾的死去活来,眼巴巴的看着CSS3中的flex,grid等更便捷更高效的的布局方式无法在项目中应用,心里那叫一个窝火啊,去你妹的兼容性,,, 最近体验下 ...
- go笔记-限速器(limiter)
参考: https://blog.csdn.net/wdy_yx/article/details/73849713https://www.jianshu.com/p/1ecb513f7632 http ...
- 解决java compiler level does not match the version of the installed java project facet【转载】
原博文地址http://blog.csdn.net/chszs/article/details/8125828 Java compiler level does not match the versi ...
- 全国天气预报信息数据 API 功能简介与代码调用实战视频
此文章对开放数据接口 API 之「全国天气预报信息数据 API」进行了功能介绍.使用场景介绍以及调用方法的说明,供用户在使用数据接口时参考之用,并对实战开发进行了视频演示. 1. 产品功能 接口开放了 ...
- (haut oj 1261 ) 地狱飞龙 利用不定积分求值
题目链接:http://218.28.220.249:50015/JudgeOnline/problem.php?id=1261 题目描述 最近clover迷上了皇室战争,他抽到了一种地狱飞龙,很开心 ...
- 删除a表中和b表相同的数据
删除a表中和b表相同的数据 - 冯索的专栏 - CSDN博客https://blog.csdn.net/wugouzi/article/details/9374329 oracle 查找A表存在B表不 ...