基础学习

/// <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. spring cloud-服务注册

    正常的服务模块,注册到注册中心,让别的服务发现,调用服务 创建“服务提供方” 下面我们创建提供服务的客户端,并向服务注册中心注册自己. 假设我们有一个提供计算功能的微服务模块,我们实现一个RESTfu ...

  2. 阮一峰 KMP BM算法

    存一个链接,讲得好啊! 点击这里打开     字符串KMP 点击这里打开     字符串匹配的Boyer-Moore算法

  3. Java中的ArrayList

    ArrayList是所谓的动态数组.用一个小例子: import java.util.ArrayList; import java.util.Iterator; import java.util.Li ...

  4. OpenMediaVault GitLab 安装

    /**************************************************************************** * OpenMediaVault GitLa ...

  5. 「LuoguP4753」濑 River Jumping(贪心

    Description 有一条宽度为 N 的河上,小D位于坐标为 0 的河岸上,他想到达坐标为 N 的河岸上后再回到坐标为 0 的位置.在到达坐标为 N 的河岸之前小D只能向坐标更大的位置跳跃,在到达 ...

  6. Codechef LOCAUG17

    做完题目很少有写题解的习惯,强行PO一组吧. 比赛链接:https://www.codechef.com/LOCAUG17 PRINCESS 给定字符串s,问s是否存在长度大于1的回文子串. 解:分两 ...

  7. SUI使用经验

    基本布局结构: 本地js.css请使用正确的路径 <!DOCTYPE html> <html> <head> <meta charset="utf- ...

  8. linux中fork对打开文件的处理

    1 子进程复制父进程的数据段.BBS段.代码段.堆空间.栈空间和文件描述符 2 对于文件描述符采用共享的方式 后面这个例子可以清晰的看出 #include <sys/types.h> #i ...

  9. 1-1 课程导学 & 1-2 项目需求分析,技术分解.

    1-1 课程导学 1-2 项目需求分析,技术分解. 要有一定的dart基础,了解安卓和ios的一些普通的开发

  10. SCUT - 243 - 宝华复习 - 二分 - 桶计数

    https://scut.online/p/243 这道题唯一难点在于如何快速确定m合法.可以统计滑动窗口中已有元素的数量. #include<bits/stdc++.h> using n ...