1:使用WebRequest向服务器发送GET请求,获取服务器的响应

1. 创建请求对象

2. 获取web响应

3. 获取web响应流

4.读取Web 流数据

完整代码如下:

    var url ="http://webcode.me";//"http://www.baidu.com";var request = WebRequest.Create(url);request.Method = "GET";using (var webResponse = request.GetResponse()){using (var webStream = webResponse.GetResponseStream()){using (var reader = new StreamReader(webStream)){var data = reader.ReadToEnd();Console.WriteLine(data);}}}

输出:

<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>My html page</title>
<p>Today is a beautiful day. We go swimming and fishing.</p><p>Hello there. How are you?</p>

2:使用WebRequest向服务器发送POST请求,获取服务器的响应

1. 创建Web请求对象

2. 指定POST方法

  1. 创建POST数据对象

  2. 将数据对象序列化为JSON字符串

5. 再将Json字符串转换为字节数组

6. 指定请求ContentType类型

7. 获取请求流对象

8. 将转换后的字节数组写入到请求流中

9. 获取请求的响应

  1. 读取响应流中的数据

完整代码如下:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using Newtonsoft.Json;

using System.Net;

using System.Net.Http;

using System.IO;

namespace _02_HTTP_POST

{

//HTTP POST//The HTTP POST method sends data to the server.//It is often used when uploading a file or when submitting a completed web form.class Program{//C# POST request with WebRequest//creates a POST request with WebRequest.static void Main(string\[\] args){var url = "https://httpbin.org/post"; //发POST请求的服务器地址var request = WebRequest.Create(url);request.Method = "POST";var user = new User("John Doe", "gardener");var json = JsonConvert.SerializeObject(user);byte\[\] byteArray = Encoding.UTF8.GetBytes(json);//序列化user对象为Json字符串,再将Json字符串转为字节数组request.ContentType = "application/json";//request.ContentType = "application/x-www-form-urlencoded";//默认地,表单数据会编码为 "application/x-www-form-urlencoded"。//就是说,在发送到服务器之前,所有字符都会进行编码(空格转换为 "+" 加号,特殊符号转换为 ASCII HEX 值)。request.ContentLength = byteArray.Length;using (var reqStream = request.GetRequestStream())//获取请求流对象{reqStream.Write(byteArray, 0, byteArray.Length);//将POST的内容传入到请求流using (var response = request.GetResponse())// 获取响应的对象{Console.WriteLine(((HttpWebResponse)response).StatusDescription);// 响应状态using (var respStream = response.GetResponseStream())// 从响应流中读取数据{using (var reader = new StreamReader(respStream)){string data = reader.ReadToEnd();Console.WriteLine(data);}}}}}}class User{public string Name { get; set; }public string Occupation { get; set; }public User(string name, string occupation){Name = name;Occupation = occupation;}public override string ToString(){return $"{Name}: {Occupation}";}}

}

输出:

OK

{

“args”: {},

“data”: “{\“Name\”:\“John Doe\”,\“Occupation\”:\“gardener\”}”,

“files”: {},

“form”: {},

“headers”: {

"Content-Length": "43","Content-Type": "application/json","Host": "httpbin.org","X-Amzn-Trace-Id": "Root=1-61aea836-517d25d562b9453c66922bab"

},

“json”: {

"Name": "John Doe","Occupation": "gardener"

},

“origin”: “180.161.88.74”,

“url”: “https://httpbin.org/post”

}

改变request.ContentType = “application/x-www-form-urlencoded”;

输出:

OK

{

“args”: {},

“data”: “”,

“files”: {},

“form”: {

"{\\"Name\\":\\"John Doe\\",\\"Occupation\\":\\"gardener\\"}": ""

},

“headers”: {

"Content-Length": "43","Content-Type": "application/x-www-form-urlencoded","Host": "httpbin.org","X-Amzn-Trace-Id": "Root=1-61aea885-2ec9f6f639d59dba53b244ad"

},

“json”: null,

“origin”: “180.161.88.74”,

“url”: “https://httpbin.org/post”

}

差异:

C# WebRequest GET/POST request相关推荐

  1. SilverLight学习笔记--Silverlight中WebRequest通讯

    本文我们学习如何使用WebRequest类实现客户端和服务器端的通讯.      本例处理过程:在客户端,我们在文本框中输入任意文本,然后用POST方法向服务器端传递信息,服务器端收到从客户端传来的信 ...

  2. 一步一步学Silverlight 2系列(13):数据与通信之WebRequest

    概述 Silverlight 2 Beta 1版本发布了,无论从Runtime还是Tools都给我们带来了很多的惊喜,如支持框架语言Visual Basic, Visual C#, IronRuby, ...

  3. Request.InputStream 将数据作为XML数据发送

    将数据作为XML数据发送,例如: public voidPostXml(stringurl, stringxml) {     byte[] bytes = Encoding.UTF8.GetByte ...

  4. C# 读取网页源码的三种办法WebClient、WebRequest、HttpWebRequest

    直接看这三种办法的源码吧, using System; using System.IO; using System.Net;namespace ReadHtml{ class ReadHtml{ st ...

  5. WebClient与WebRequest差异

    WebRequst的使用 WebClient和HttpWebRequst是用来获取数据的2种方式,在我的这篇数据访问(2)中主要是讲的WebClient的使用,一般而言,WebClient更倾向于&q ...

  6. ASP.NET中Request.InputStream使用

    将数据作为XML数据发送,例如: public void PostXml(string url, string xml) {    byte[] bytes = Encoding.UTF8.GetBy ...

  7. WebRequest 类

    WebRequest 类 Sys.Net.WebRequest 类 提供用于发出 Web 请求的客户端脚本功能. 命名空间:Sys.Net 继承:无 var wRequest = new Sys.Ne ...

  8. C# 使用WebRequest发送post和get请求

    目录 1.get请求方式 1.1不需要请求参数时 1.2请求参数可以用表单数据(键值对)拼接时 2.POST请求方式 2.1请求参数为json字符串格式时 2.2请求参数为表单数据(键值对)格式时 2 ...

  9. 网络编程--ftp客户端的实现(c#版)

    .net2.0对ftp有了一个很好的封装,但是确容易让人忽略ftp的真正内部实现,下面是我实现的ftp客户端的功能,其主要步骤是这样的: 1.创建一个FtpWebRequest对象,指向ftp服务器的 ...

最新文章

  1. 用户家目录下的隐藏文件
  2. 能迂回,会绕路的开源游戏AI:解决怪物撞墙卡死角
  3. Eclipse 安装 SVN 插件
  4. 光线追踪技术的理论和实践(面向对象)
  5. Qt智能指针--QScopedPointer
  6. LANGUAGE MODELS ARE OPEN KNOWLEDGE GRAPHS —— 读后总结
  7. 使用Spring Boot应用程序将代码管道化
  8. rn 实现上下滑动选择列表_用大前端技术实现的一款仿Boss直聘app(已开源)
  9. Qt工作笔记-QGraphics重设场景坐标【标签:Qt图形框架】
  10. 智能文档分析:NLP和OCR的融合技术
  11. 记一次SVN误删除操作和Tomcat版本与操作系统不兼容 问题分析及解决的过程
  12. 自学python能找到工作吗-自学Python如何找工作?多久能找到工作?
  13. Android-【报错】java.lang.ClassCastException: .MainActivity cannot be cast to java.lang.Runnable
  14. 使用LoadBalancerClient就行服务消费
  15. 【SPSS】包含多元线性回归、聚类分析、判别分析、主成分、相关系数、非参数秩检验的spss使用方法,含有相关例题,可以解决“数学建模”中数据建模的大部分问题
  16. mysql 基础 红黑联盟_[转载]mysql日期加减 – mysql数据库栏目 – 红黑联盟
  17. java接口保存文件到本地指定目录下
  18. 【Microsoft Azure 的1024种玩法】十五.通过Web浏览器对Auzre VM 服务器运维管理
  19. 音频和语音处理领域CCF期刊和杂志
  20. ESXi-6.7.0-20191204001-standard-RTL8111.iso集成第三方网卡驱动

热门文章

  1. 来凯医药冲刺港交所上市:斥巨资购买专利许可权,将持续受制于人
  2. 为Gerrit Code review添加verified标签
  3. laravel-admin 结合搭配商品sku
  4. win11点击任务栏快捷方式出现“该文件没有与之关联的应用来执行该操作”解决方法
  5. 数字孪生场景、代码即开即用 | 图观引擎 超详细功能范例演示
  6. springboot中mybatisplus基于注解的多对多级联查询
  7. 阀盖零件/汽车连杆/发动机连杆/左支座/后钢板弹簧吊耳/法兰盘/拨叉/轴承座/后托架/齿轮油泵泵体/手柄座/杠杆/连接座/手柄套/十字头零件/活塞……加工工艺及夹具毕业设计、课程设计题目推荐
  8. 网页获取微信信息——js使用插件生成二维码(1)
  9. 八年级英语外研版下第二学期英语阶段测试卷(Module 5)
  10. Mysql8.0 添加用户和权限