提供基于HttpWebRequest的请求的应用类,其中包含:get请求(带参或不带参)、post请求、文件传输请求

方法的具体说明:

PostHttp:post请求,支持三种提交模式:FROM、JSON、XML

GetHttp:get请求(带参或不带参)

PostFile:文件传输请求

/// <summary>
/// 提供HttpWebRequest请求的相关封装.
/// 本接口所提供的方法均不含异常拦截处理,请在调用的主方法中去拦截请求异常.
/// </summary>
public static class Request
{
#region post 请求
public enum PostType
{
/// <summary>
/// 表单模式,传入参数格式如:roleId=1&uid=2
/// </summary>
FROM = ,
/// <summary>
/// JSON格式字符串,格式如:{k:v,k2:v2,k3:{kk1:vv1}}
/// </summary>
JSON = ,
/// <summary>
/// XML模式
/// </summary>
XML =
}
public static string PostHttp(string url, string body, PostType type = PostType.FROM)
{
string resStr = string.Empty;
switch (type)
{
case PostType.FROM:
resStr = PostForm(url, body);
break;
case PostType.JSON:
resStr = PostJson(url, body);
break;
case PostType.XML:
resStr = PostXml(url, body);
break;
default:
resStr = PostForm(url, body);
break;
}
return resStr;
} #region post请求几种方式(私有)
/// <summary>
/// POST表单
/// </summary>
/// <param name="url"></param>
/// <param name="body"></param>
/// <returns></returns>
private static string PostForm(string url, string body)
{
string resStr = string.Empty;
byte[] bs = Encoding.UTF8.GetBytes(body);
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = bs.Length; using (Stream reqStream = myRequest.GetRequestStream())
{
reqStream.Write(bs, , bs.Length);
} using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse())
{
StreamReader sr = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
resStr = sr.ReadToEnd();
sr.Close();
}
myRequest.Abort();
return resStr;
} /// <summary>
/// POST XML
/// </summary>
/// <param name="url">请求url(不含参数)</param>
/// <param name="body">请求body. soap"text/xml; charset=utf-8"xml字符串</param>
/// <returns></returns>
private static string PostXml(string url, string body)
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.ContentType = "text/xml;charset=utf-8";
httpWebRequest.Method = "POST";
//httpWebRequest.Timeout = timeout;//设置超时
httpWebRequest.Headers.Add("SOAPAction", "http://tempuri.org/mediate"); byte[] btBodys = Encoding.UTF8.GetBytes(body);
httpWebRequest.ContentLength = btBodys.Length;
httpWebRequest.GetRequestStream().Write(btBodys, , btBodys.Length); #region 取消异常拦截
//HttpWebResponse httpWebResponse;
//try
//{
// httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
//}
//catch (WebException ex)
//{
// httpWebResponse = (HttpWebResponse)ex.Response;
//}
#endregion HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
string responseContent = streamReader.ReadToEnd(); httpWebResponse.Close();
streamReader.Close();
httpWebRequest.Abort(); return responseContent;
} /// <summary>
/// POST json
/// </summary>
/// <param name="url"></param>
/// <param name="JSONData"></param>
/// <returns></returns>
private static string PostJson(string url, string JSONData)
{
string result = string.Empty;
//byte[] bs = Encoding.UTF8.GetBytes(body);
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
myRequest.Method = "POST";
myRequest.ContentType = "application/json"; using (var streamWriter = new StreamWriter(myRequest.GetRequestStream()))
{
streamWriter.Write(JSONData);
streamWriter.Flush();
streamWriter.Close();
} var httpResponse = (HttpWebResponse)myRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
} httpResponse.Close();
myRequest.Abort();
return result;
}
#endregion #endregion #region get请求
/// <summary>
/// get请求
/// </summary>
/// <param name="url">请求url(不含参数)</param>
/// <param name="postDataStr">参数部分:roleId=1&uid=2</param>
/// <param name="timeout">等待时长(毫秒)</param>
/// <returns></returns>
public static string GetHttp(string url, string postDataStr,int timeout=)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + (postDataStr == "" ? "" : "?") + postDataStr);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
request.Timeout = timeout;//等待 HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close(); response.Close();
request.Abort();
return retString;
}
#endregion #region 文件传输请求
/// <summary>
/// 传输文件到指定接口
/// </summary>
/// <param name="url"></param>
/// <param name="filePath">文件物理路径</param>
/// <returns></returns>
public static string PostFile(string url, string filePath)
{
string resStr = string.Empty; // 初始化HttpWebRequest
HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(url); // 封装Cookie
Uri uri = new Uri(url);
Cookie cookie = new Cookie("Name", DateTime.Now.Ticks.ToString());
CookieContainer cookies = new CookieContainer();
cookies.Add(uri, cookie);
httpRequest.CookieContainer = cookies; if (!File.Exists(filePath))
{
return "文件不存在";
}
FileInfo file = new FileInfo(filePath); // 生成时间戳
string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
byte[] boundaryBytes = Encoding.ASCII.GetBytes(string.Format("\r\n--{0}--\r\n", strBoundary)); // 填报文类型
httpRequest.Method = "Post";
httpRequest.Timeout = * ;
httpRequest.ContentType = "multipart/form-data; boundary=" + strBoundary; // 封装HTTP报文头的流
StringBuilder sb = new StringBuilder();
sb.Append("--");
sb.Append(strBoundary);
sb.Append(Environment.NewLine);
sb.Append("Content-Disposition: form-data; name=\"");
sb.Append("file");
sb.Append("\"; filename=\"");
sb.Append(file.Name);
sb.Append("\"");
sb.Append(Environment.NewLine);
sb.Append("Content-Type: ");
sb.Append("multipart/form-data;");
sb.Append(Environment.NewLine);
sb.Append(Environment.NewLine);
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sb.ToString()); // 计算报文长度
long length = postHeaderBytes.Length + file.Length + boundaryBytes.Length;
httpRequest.ContentLength = length; // 将报文头写入流
Stream requestStream = httpRequest.GetRequestStream();
requestStream.Write(postHeaderBytes, , postHeaderBytes.Length); byte[] buffer = new byte[];
int bytesRead = ;
using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
while ((bytesRead = fileStream.Read(buffer, , buffer.Length)) != )
{
requestStream.Write(buffer, , bytesRead);
}
} // 将报文尾部写入流
requestStream.Write(boundaryBytes, , boundaryBytes.Length);
// 关闭流
requestStream.Close(); using (HttpWebResponse myResponse = (HttpWebResponse)httpRequest.GetResponse())
{
StreamReader sr = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
resStr = sr.ReadToEnd();
sr.Close();
//Console.WriteLine("反馈结果" + responseString);
}
httpRequest.Abort();
return resStr;
}
#endregion
}

.NET HttpWebRequest应用的更多相关文章

  1. 利用HttpWebRequest实现实体对象的上传

    一 简介 HttpWebRequest和HttpWebResponse类是用于发送和接收HTTP数据的最好选择.它们支持一系列有用的属性.这两个类位 于System.Net命名空间,默认情况下这个类对 ...

  2. C#通过WebClient/HttpWebRequest实现http的post/get方法

    C#通过WebClient/HttpWebRequest实现http的post/get方法 http://www.cnblogs.com/shadowtale/p/3372735.html

  3. C# HttpWebRequest获取COOKIES

    C# HttpWebRequest获取COOKIES byte[] bytes = Encoding.Default.GetBytes(_post); CookieContainer myCookie ...

  4. 在使用 HttpWebRequest Post数据时候返回 400错误

    笔者有一个项目中用到了上传zip并解压的功能.开始觉得很简单,因为之前曾经做过之类的上传文件的功能,所以并不为意,于是使用copy大法.正如你所料,如果一切很正常的能运行的话就不会有这篇笔记了. 整个 ...

  5. .net学习笔记----HttpRequest,WebRequest,HttpWebRequest区别

    WebRequest是一个虚类/基类,HttpWebRequest是WebRequest的具体实现 HttpRequest类的对象用于服务器端,获取客户端传来的请求的信息,包括HTTP报文传送过来的所 ...

  6. C#使用HttpWebRequest 进行请求,提示 基础连接已经关闭: 发送时发生错误。

    本人今天遇到的错误,C#使用HttpWebRequest 进行请求,提示 基础连接已经关闭: 发送时发生错误. 测试了很久,才发现,是安全协议问题,把安全协议加上就可以了

  7. C# winfrom HttpWebRequest 请求获取html网页信息和提交信息

    string result =GetRequest("http://localhost:32163/DuoBao/ajax.aspx", "time=5"); ...

  8. ASP.NET中使用HttpWebRequest调用WCF

    最近项目需要和第三网站进行数据交换,第三方网站基本都是RESTfull形式的API,但是也有的是Web Service,或者.NET里面的WCF.微软鼓励大家使用WCF替代Web Service. W ...

  9. 【转】asp.net(c#)使用HttpWebRequest附加携带请求参数以post方式模拟上传大文件(以图片为例)到Web服务器端

    原文地址:http://docode.top/Article/Detail/10002 目录: 1.Http协议上传文件(以图片为例)请求报文体内容格式 2.完整版HttpWebRequest模拟上传 ...

  10. .Net(c#)模拟Http请求之HttpWebRequest封装

    一.需求: 向某个服务发起请求获取数据,如:爬虫,采集. 二.步骤(HttpWebRequest): 无非在客户端Client(即程序)设置请求报文(如:Method,Content-Type,Age ...

随机推荐

  1. live555 基本框架

    (转) 从程序的结构来看,live项目包括了四个基本库.程序入口类(在mediaServer中)和一些测试代码(在testProgs中).四个基本库是UsageEnvironment,BasicUsa ...

  2. (待做例子)问题描述: el-tab 下有2个路由,其中第1个路由设置了 beforeRouteLeave,点击 el-tab 第2个tab时,样式直接跟过去了(预期结果是:样式不到第二个tab上,beforeRouteLeave允许跳转后才到第二个tab上)

    解决: 经过以上分析,强制赋值应该在前次赋值而且DOM已经刷新完毕之后进行.可以使用$nextTick,以下是代码: handleTabClick (tab) { let name = this.fi ...

  3. Linux shell脚本基础学习详细介绍(完整版)二

    详细介绍Linux shell脚本基础学习(五) Linux shell脚本基础前面我们在介绍Linux shell脚本的控制流程时,还有一部分内容没讲就是有关here document的内容这里继续 ...

  4. 类数组对象与arguments

    类数组对象 所谓的类数组对象: 拥有一个 length 属性和若干索引属性的对象 举个例子: var array = ['name', 'age', 'sex']; var arrayLike = { ...

  5. React.js 小书

    http://huziketang.mangojuice.top/books/react/

  6. 项目构建工具ant的使用

    ant是项目构建工具,以xml文件作为构建文件,在这个xml文件(默认是build.xml,当然也可以取其它名字)里我们可以定义多个目标,用我们期待的方式去构建项目,比如说编译,测试,发邮件等等. a ...

  7. Robots 2019南京网络赛 (概率dp)

    Robots \[ Time Limit: 1000 ms \quad Memory Limit: 262144 kB \] 题意 有一个机器人要从 \(1\) 点走到 \(n\) 点,每走一步都需要 ...

  8. MongoDB 部署复制集(副本集)

    部署MongoDB复制集(副本集)   环境 操作系统:Ubuntu 18.04 MongoDB: 4.0.3 服务器 首先部署3台服务器,1台主节点 + 2台从节点 3台服务器的内容ip分别是: 1 ...

  9. make命令与Makefile(转载)

    概述博客内容包含linux下make命令的使用与makefile的书写规则等,希望通过本文档使读者对make命令makefile文件有进一步了解,由于鄙人经验学识有限文档中会有描述不准确以及理解偏差, ...

  10. 小胖守皇宫(VIJOS P1144 )题解

    题目描述 huyichen世子事件后,xuzhenyi成了皇上特聘的御前一品侍卫. 皇宫以午门为起点,直到后宫嫔妃们的寝宫,呈一棵树的形状:某些宫殿间可以互相望见.大内保卫森严,三步一岗,五步一哨,每 ...