基础学习

/// <summary>
/// Http (GET/POST)
/// </summary>
/// <param name="url">请求URL</param>
/// <param name="parameters">请求参数</param>
/// <param name="method">请求方法</param>
/// <returns>响应内容</returns>
static string sendPost(string url, IDictionary<string, string> parameters, string method)
{
if (method.ToLower() == "post")
{
HttpWebRequest req = null;
HttpWebResponse rsp = null;
System.IO.Stream reqStream = null;
try
{
req = (HttpWebRequest)WebRequest.Create(url);
req.Method = method;
req.KeepAlive = false;
req.ProtocolVersion = HttpVersion.Version10;
req.Timeout = ;
req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
byte[] postData = Encoding.UTF8.GetBytes(BuildQuery(parameters, "utf8"));
reqStream = req.GetRequestStream();
reqStream.Write(postData, , postData.Length);
rsp = (HttpWebResponse)req.GetResponse();
Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
return GetResponseAsString(rsp, encoding);
}
catch (Exception ex)
{
return ex.Message;
}
finally
{
if (reqStream != null) reqStream.Close();
if (rsp != null) rsp.Close();
}
}
else
{
//创建请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "?" + BuildQuery(parameters, "utf8")); //GET请求
request.Method = "GET";
request.ReadWriteTimeout = ;
request.ContentType = "text/html;charset=UTF-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); //返回内容
string retString = myStreamReader.ReadToEnd();
return retString;
}
}

方法代码

public HttpWebRequest GetWebRequest(string url, string method)
{
HttpWebRequest request = null;
if (url.Contains("https"))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(this.CheckValidationResult);
request = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
}
else
{
request = (HttpWebRequest)WebRequest.Create(url);
}
request.ServicePoint.Expect100Continue = false;
request.Method = method;
request.KeepAlive = true;
request.UserAgent = "stgp";
return request;
} /// <summary>
/// 解决使用上面方法向同一个地址发送请求时会发生:基础连接已经关闭: 服务器关闭了本应保持活动状态的连接的问题
/// </summary>
/// <param name="url"></param>
/// <param name="method"></param>
/// <returns></returns>
public HttpWebRequest GetWebRequestDotnetReference(string url, string method)
{
HttpWebRequest request = null;
if (url.Contains("https"))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(this.CheckValidationResult);
request = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
}
else
{
request = (HttpWebRequest)WebRequest.Create(url);
} request.Method = method;
request.KeepAlive = false;//fase
request.ProtocolVersion = HttpVersion.Version11;//Version11
request.UserAgent = "stgp";
return request;
}

方法代码

/// <summary>
/// 组装普通文本请求参数。
/// </summary>
/// <param name="parameters">Key-Value形式请求参数字典</param>
/// <returns>URL编码后的请求数据</returns>
static string BuildQuery(IDictionary<string, string> parameters, string encode)
{
StringBuilder postData = new StringBuilder();
bool hasParam = false;
IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
while (dem.MoveNext())
{
string name = dem.Current.Key;
string value = dem.Current.Value;
// 忽略参数名或参数值为空的参数
if (!string.IsNullOrEmpty(name))//&& !string.IsNullOrEmpty(value)
{
if (hasParam)
{
postData.Append("&");
}
postData.Append(name);
postData.Append("=");
if (encode == "gb2312")
{
postData.Append(HttpUtility.UrlEncode(value, Encoding.GetEncoding("gb2312")));
}
else if (encode == "utf8")
{
postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
}
else
{
postData.Append(value);
}
hasParam = true;
}
}
return postData.ToString();
}

方法代码

/// <summary>
/// 把响应流转换为文本。
/// </summary>
/// <param name="rsp">响应流对象</param>
/// <param name="encoding">编码方式</param>
/// <returns>响应文本</returns>
static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
{
System.IO.Stream stream = null;
StreamReader reader = null;
try
{
// 以字符流的方式读取HTTP响应
stream = rsp.GetResponseStream();
reader = new StreamReader(stream, encoding);
return reader.ReadToEnd();
}
finally
{
// 释放资源
if (reader != null) reader.Close();
if (stream != null) stream.Close();
if (rsp != null) rsp.Close();
}
}

方法代码

string url = "http://www.example.com/api/exampleHandler.ashx";
var parameters = new Dictionary<string, string>();
parameters.Add("param1", "");
parameters.Add("param2", ""); string result = sendPost(url, parameters, "get");

使用示例

进阶学习

一、读取本地图片文件,进行上传

public string DoPostWithFile(string url, IDictionary<string, string> textParams, List<string> filePathList, string charset = "utf-8")
{
string boundary = "-------" + DateTime.Now.Ticks.ToString("X"); // 随机分隔线 HttpWebRequest req = GetWebRequestDotnetReference(url, "POST");
req.ContentType = "multipart/form-data;charset=" + charset + ";boundary=" + boundary; System.IO.Stream reqStream = req.GetRequestStream();
byte[] itemBoundaryBytes = Encoding.GetEncoding(charset).GetBytes("\r\n--" + boundary + "\r\n");
byte[] endBoundaryBytes = Encoding.GetEncoding(charset).GetBytes("\r\n--" + boundary + "--\r\n"); // 组装文本请求参数
string textTemplate = "Content-Disposition:form-data;name=\"{0}\"\r\nContent-Type:text/plain\r\n\r\n{1}";
IEnumerator<KeyValuePair<string, string>> textEnum = textParams.GetEnumerator();
while (textEnum.MoveNext())
{
string textEntry = string.Format(textTemplate, textEnum.Current.Key, textEnum.Current.Value);
byte[] itemBytes = Encoding.GetEncoding(charset).GetBytes(textEntry);
reqStream.Write(itemBoundaryBytes, , itemBoundaryBytes.Length);
reqStream.Write(itemBytes, , itemBytes.Length);
} // 组装文件请求参数
#region 将文件转成二进制
string fileName = string.Empty;
byte[] fileContentByte = new byte[]; string fileTemplate = "Content-Disposition:form-data;name=\"{0}\";filename=\"{1}\"\r\n\r\n";
foreach (string filePath in filePathList)
{
fileName = filePath.Substring(filePath.LastIndexOf("\\") + ); FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
fileContentByte = new byte[fs.Length];
fs.Read(fileContentByte, , Convert.ToInt32(fs.Length));
fs.Close(); string fileEntry = string.Format(fileTemplate, "images[]", fileName);
byte[] itemBytesF = Encoding.GetEncoding(charset).GetBytes(fileEntry);
reqStream.Write(itemBoundaryBytes, , itemBoundaryBytes.Length);
reqStream.Write(itemBytesF, , itemBytesF.Length);
reqStream.Write(fileContentByte, , fileContentByte.Length);
}
#endregion reqStream.Write(endBoundaryBytes, , endBoundaryBytes.Length);
reqStream.Close(); HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
return GetResponseAsString(rsp, encoding);
}

方法代码

string url = "http://www.example.com/api/exampleHandler.ashx";
var param = new Dictionary<string, string>();
param.Add("param1", "");
List<string> filePathList = new List<string>();
filePathList.Add(@"C:\Users\pic1.png"); string result = DoPostWithFile(url, param, filePathList);

使用示例

二、读取网络上的图片文件,进行上传

public string DoPostWithNetFile(string url, IDictionary<string, string> textParams, List<string> filePathList, string charset = "utf-8")
{
string boundary = "-------" + DateTime.Now.Ticks.ToString("X"); // 随机分隔线 //HttpWebRequest req = GetWebRequest(url, "POST");
HttpWebRequest req = GetWebRequestDotnetReference(url, "POST");
req.ContentType = "multipart/form-data;charset=" + charset + ";boundary=" + boundary; System.IO.Stream reqStream = req.GetRequestStream();
byte[] itemBoundaryBytes = Encoding.GetEncoding(charset).GetBytes("\r\n--" + boundary + "\r\n");
byte[] endBoundaryBytes = Encoding.GetEncoding(charset).GetBytes("\r\n--" + boundary + "--\r\n"); // 组装文本请求参数
string textTemplate = "Content-Disposition:form-data;name=\"{0}\"\r\nContent-Type:text/plain\r\n\r\n{1}";
IEnumerator<KeyValuePair<string, string>> textEnum = textParams.GetEnumerator();
while (textEnum.MoveNext())
{
string textEntry = string.Format(textTemplate, textEnum.Current.Key, textEnum.Current.Value);
byte[] itemBytes = Encoding.GetEncoding(charset).GetBytes(textEntry);
reqStream.Write(itemBoundaryBytes, , itemBoundaryBytes.Length);
reqStream.Write(itemBytes, , itemBytes.Length);
} // 组装文件请求参数
#region 将文件转成二进制
string fileName = string.Empty;
byte[] fileContentByte = new byte[]; string fileTemplate = "Content-Disposition:form-data;name=\"{0}\";filename=\"{1}\"\r\n\r\n";
foreach (string filePath in filePathList)
{
fileName = filePath.Substring(filePath.LastIndexOf(@"/") + ); HttpWebRequest imgRequest = (HttpWebRequest)WebRequest.Create(filePath);
imgRequest.Method = "GET";
using (HttpWebResponse imgResponse = imgRequest.GetResponse() as HttpWebResponse)
{
if (imgResponse.StatusCode == HttpStatusCode.OK)
{
Stream rs = imgResponse.GetResponseStream(); MemoryStream ms = new MemoryStream();
const int bufferLen = ;
byte[] buffer = new byte[bufferLen];
int count = ;
while ((count = rs.Read(buffer, , bufferLen)) > )
{
ms.Write(buffer, , count);
} ms.Seek(, SeekOrigin.Begin); int buffsize = (int)ms.Length; //rs.Length 此流不支持查找,先转为MemoryStream
fileContentByte = new byte[buffsize]; ms.Read(fileContentByte, , buffsize);
ms.Flush(); ms.Close();
rs.Flush(); rs.Close();
}
} string fileEntry = string.Format(fileTemplate, "images[]", fileName);
byte[] itemBytesF = Encoding.GetEncoding(charset).GetBytes(fileEntry);
reqStream.Write(itemBoundaryBytes, , itemBoundaryBytes.Length);
reqStream.Write(itemBytesF, , itemBytesF.Length);
reqStream.Write(fileContentByte, , fileContentByte.Length);
}
#endregion reqStream.Write(endBoundaryBytes, , endBoundaryBytes.Length);
reqStream.Close(); HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
return GetResponseAsString(rsp, encoding);
}

方法代码

string url = "http://www.example.com/api/exampleHandler.ashx";
var param = new Dictionary<string, string>();
param.Add("param1", "");
List<string> filePathList = new List<string>();
filePathList.Add(@"http://www.example.com/img/pic1.png"); string result = DoPostWithNetFile(url, param, filePathList);

使用示例

【C#】.net 发送get/post请求的更多相关文章

  1. 如果调用ASP.NET Web API不能发送PUT/DELETE请求怎么办?

    理想的RESTful Web API采用面向资源的架构,并使用请求的HTTP方法表示针对目标资源的操作类型.但是理想和现实是有距离的,虽然HTTP协议提供了一系列原生的HTTP方法,但是在具体的网络环 ...

  2. 调用webapi 错误:使用 HTTP 谓词 POST 向虚拟目录发送了一个请求,而默认文档是不支持 GET 或 HEAD 以外的 HTTP 谓词的静态文件。的解决方案

    第一次调用webapi出错如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http:// ...

  3. 从零开始学习Node.js例子七 发送HTTP客户端请求并显示响应结果

    wget.js:发送HTTP客户端请求并显示响应的各种结果 options对象描述了将要发出的请求.data事件在数据到达时被触发,error事件在发生错误时被触发.HTTP请求中的数据格式通过MIM ...

  4. 使用 HttpWebRequest 发送模拟 POST 请求

    使用HttpWebRequest发送模拟POST请求  网页中,如果form的method="POST",这时点击submit按钮可以给服务器发送了一个POST请求,如果metho ...

  5. IOS学习之路十八(通过 NSURLConnection 发送 HTTP 各种请求)

    你想通过 Http 协议向服务器发送一个 Get 的包装请求,并在这个请求中添加了一些请 求参数. 向远程服务器发送一个 GET 请求,然后解析返回的数据.通常一个 GET 请求是添加了 一些参数的, ...

  6. 发送POST测试请求的若干方法

    最近在工作中需要测试发送带Json格式body值的HTTP POST请求.起初,我在Linux环境下使用curl命令去发送请求,但是,在发送的过程中却遇到了一些问题,经过一段时间的摸索,发现了以下几种 ...

  7. Postman教程——发送第一个请求

    系列文章首发平台为果冻想个人博客.果冻想,是一个原创技术文章分享网站.在这里果冻会分享他的技术心得,技术得失,技术人生.我在果冻想等待你,也希望你能和我分享你的技术得与失,期待. 前言 过年在家,闲来 ...

  8. charles重复发送一个网络请求&同时发送N次

    重发网络请求的目的:后端调试的过程中,一直在客户端进行点点点比较麻烦,此时直接发送请求比较方便查看调试后的结果(方便后端调试) 1.重复发送一个请求(有两种方法) (1)选定该请求,右键选择repea ...

  9. [Postman]发送第一个请求(1)

    通过API请求,您可以与具有要访问的API端点的服务器联系,并执行某些操作.这些操作是HTTP方法. 最常用的方法是GET,POST,PUT和DELETE.方法的名称是不言自明的.例如,GET使您可以 ...

  10. java发送http get请求的两种方式

    长话短说,废话不说 一.第一种方式,通过HttpClient方式,代码如下: public static String httpGet(String url, String charset) thro ...

随机推荐

  1. Deep Learning 32: 自己写的keras的一个callbacks函数,解决keras中不能在每个epoch实时显示学习速率learning rate的问题

    一.问题: keras中不能在每个epoch实时显示学习速率learning rate,从而方便调试,实际上也是为了调试解决这个问题:Deep Learning 31: 不同版本的keras,对同样的 ...

  2. 关于npm的环境变量配置、prefix

    1.关于npm 的 prefix 在npm中安装全局文件时,npm会把他安装在npm里面配置的prefix路径下,查看prefix的方法是:npm config list/npm config ls/ ...

  3. git push & git pull 推送/拉取指定分支

    https://blog.csdn.net/litianze99/article/details/52452521

  4. eclipse输入提示 设置

  5. 微信公众号菜单与应用交互session

    http://www.cnblogs.com/yank/p/3476874.html http://blog.csdn.net/zmhawk/article/details/43671195 http ...

  6. html5--6-5 CSS选择器2

    html5--6-5 CSS选择器2 实例 学习要点 掌握常用的CSS选择器 了解不太常用的CSS选择器 什么是选择器 当我们定义一条样式时候,这条样式会作用于网页当中的某些元素,所谓选择器就是样式作 ...

  7. Python项目使用memcached缓存

    前言许多Web应用都将数据保存到MySQL这样的关系型数据库管理系统中,应用服务器从中读取数据并在浏览器中显示. 但随着数据量的增大.访问的集中,就会出现数据库的负担加重.数据库响应恶化. 网站显示延 ...

  8. 聊聊Java SPI机制

    一.Java SPI机制 SPI(Service Provider Interface)是JDK内置的服务发现机制,用在不同模块间通过接口调用服务,避免对具体服务服务接口具体实现类的耦合.比如JDBC ...

  9. node.js适合游戏后台开发吗?

    网站服务器和游戏服务器是怎么样联系到一起的? 百牛信息技术bainiu.ltd整理发布于博客园 1. 游戏分很多种,咱们先来看看MMORPG. 再怎么简单的RPG服务器都免不了处理多人交互的情形,上百 ...

  10. PYTHON XPath与lxml类库

    XPath,我们可以用先将HTML文档转换成XML文档,然后用XPath查找HTML节点或元素. XML文档实例 HTML DOM模型示例 HTML DOM定义了访问和操作HTML文档的标准方法,以树 ...