很久不更新博客了,这次大概说一下c#中的send webrequest,众所周知,.net网络编程在测试中是非常常见的,具体来说,比如我们如果测试一个api,通过send webrequest的方式来进行api层面的功能测试,然后用selenium完成前端的验证,这种模式应该说是比较方便而通用的,具体以其中最常见的http request为例,当我们需要传输数据时,需要
1)地址:address作为webrequest参数实例化,然后设定相应属性,比如method(get还是post等等)
2)数据:data作为httprequest的数据流写入:
xmlresponse = null;
responsecode = httpstatuscode.unused;
serverresponse = string.empty;
参数处理部分
//format the data
string output = data.aggregate(string.empty, (current, keyvaluepair) => current + ("&" + keyvaluepair.key + "=" + httputility.urlencode(keyvaluepair.value)));
var encoding = new utf8encoding();
//设置postdata变量将output进行处理,最终得到byte[] d作为最终数据写入到webrequest中
var postdata = encoding.ascii.getbytes(output);
byte[] d = encoding.getbytes(output.substring(1, output.length - 1));
var address = targeturl;
//get部分的数据处理
if (method.toupperinvariant() == "get")
address=address+output;
//post部分的数据处理
webrequest request = webrequest.create(address) as httpwebrequest;
//add post process
if (request == null)
throw new exception("webrequest object is null.");
request.method = "post";
request.contenttype = "application/x-www-form-urlencoded";
request.contentlength = d.length;
serverresponse = string.empty;
//数据读取及处理部分
using (stream datastream = request.getrequeststream())
{
datastream.write(d, 0, d.length);
datastream.close();
using (var response = (httpwebresponse)request.getresponse())
{
responsecode = response.statuscode;
using (stream mystream = response.getresponsestream())
{
if (mystream != null)
{
var readstream = new streamreader(mystream, encoding.utf8);
serverresponse = readstream.readtoend();
}
}
response.close();
}
}
if (responsecode == httpstatuscode.ok)
{
if (loadxml)
loadxml();
return true;
}
return false;
C#中关于Send WebRequest 方法和数据处理
来源:这里教程网
时间:2026-02-21 13:05:12
作者:
编辑推荐:
- C#中关于Send WebRequest 方法和数据处理02-21
- .net c# 正则表达式 平衡组/递归匹配02-21
- .net中XML转换成TreeView视图02-21
- ASP.NET 使用Ajax02-21
- C#常用GDI+文字操作汇总02-21
- C# GDI+技术02-21
- 浅谈C#使用GDI+02-21
- C# GDI+编程(四)02-21
下一篇:
相关推荐
-
雷神推出 MIX PRO II 迷你主机:基于 Ultra 200H,玻璃上盖 + ARGB 灯效
2 月 9 日消息,雷神 (THUNDEROBOT) 现已宣布推出基于英
-
制造商 Musnap 推出彩色墨水屏电纸书 Ocean C:支持手写笔、第三方安卓应用
2 月 10 日消息,制造商 Musnap 现已在海外推出一款 Oce
热文推荐
- ASP.NET 使用Ajax
ASP.NET 使用Ajax
26-02-21 - C#常用GDI+文字操作汇总
C#常用GDI+文字操作汇总
26-02-21 - Asp.net Jquery Ajax 实例
Asp.net Jquery Ajax 实例
26-02-21 - C#的索引器
C#的索引器
26-02-21 - C#中的索引器的简单理解和用法
C#中的索引器的简单理解和用法
26-02-21 - C#中的索引器的简单理解和用法
C#中的索引器的简单理解和用法
26-02-21 - c# GDI+简单绘图(二)
c# GDI+简单绘图(二)
26-02-21 - 深入理解C#索引器(一种支持参数的属性)与属性的对比
深入理解C#索引器(一种支持参数的属性)与属性的对比
26-02-21 - c# GDI+简单绘图(一)
c# GDI+简单绘图(一)
26-02-21 - c# GDI+简单绘图(四)
c# GDI+简单绘图(四)
26-02-21
