提供基于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. 1062 Error 'Duplicate entry '1438019' for key 'PRIMARY'' on query

    mysql主从库同步错误:1062 Error 'Duplicate entry '1438019' for key 'PRIMARY'' on querymysql主从库在同步时会发生1062 La ...

  2. python应用-猜数字

    """ 猜数字游戏(电脑给数字人猜) Author:罗万财 Date:2017-6-3 """ from random import ran ...

  3. MySQL 8.x 函数和操作符,官方网址:https://dev.mysql.com/doc/refman/8.0/en/functions.html

    MySql 8.x 函数和操作符,官方网址:https://dev.mysql.com/doc/refman/8.0/en/functions.html

  4. React Hook Flow Diagram

    一.概述 Donovon has created this nice flowchart that explains the new lifecycle of a Hooks component. C ...

  5. DOM是什么

    UI—html—DOM(tree-structured representation. manipulate)—Virtual DOM(component) Real DOM强调树状结构的整体:核心是 ...

  6. 重温Elasticsearch

    什么是 Elasticsearch ? Elasticsearch (ES) 是一个基于 Lucene 构建的开源.分布式.RESTful 接口全文搜索引擎.还是一个分布式文档数据库,其中每个字段均是 ...

  7. new String("123") 创建了几个对象?

    String 对象可谓再熟悉不过了,与此相关的面试题经常会引出内存性能优化的问题,本篇主要以 new String("123") 创建了几个对象为例记录. 一.你能回答正确吗 St ...

  8. Reincarnation HDU - 4622 (后缀自动机)

    Reincarnation \[ Time Limit: 3000 ms\quad Memory Limit: 65536 kB \] 题意 给出一个字符串 \(S\),然后给出 \(m\) 次查询, ...

  9. OpenCV实现"你的名字"滤镜

    这是一个比较有意思的demo,用到了播送融合,具体效果见下图: 文件结构如图所示 主程序代码 #include"stdafx.h" #include<opencv2/phot ...

  10. MySQL的简单概念及软件安装

    数据库的简介 一.数据库的基本概念:数据.数据库.数据库管理系统.数据库系统 数据:数据(Data)是用来记录信息的可识别符号,是信息的具体表现形式. 数据库:(1)数据库(Database,DB)是 ...