基础学习

/// <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. 浅谈HTTPS连接

    相信很多朋友都遇到过网页被强插广告的情况,好端端一个干净的页面,动不动就被插了个屠龙宝刀点击就送的小窗口,看着就心烦.这种网页劫持强插广告的现象,在中国非常常见,往往是运营商进行HTTP劫持所造成的. ...

  2. JSP JDBC 读取SQL Server 数据2

    <%-- Created by IntelliJ IDEA. User: hellohongfu Date: 2017/12/21 Time: 0:16 To change this templ ...

  3. CentOS7.2安装Vim8和YouCompleteMe

    1.环境 本文使用VMWare虚拟机进行实验,客户机系统是CentOS 7.2最小安装(CentOS-7-x86_64-Minimal-1511.iso) 最终实现效果:安装vim8 + python ...

  4. Redis持久化(RDB和AOF)

    什么是Redis持久化 什么是Redis持久化,就是将内存数据保存到硬盘. Redis 持久化存储 (AOF 与 RDB 两种模式) RDB持久化 RDB 是以二进制文件,是在某个时间 点将数据写入一 ...

  5. Spring配置错误 No adapter for IAdvice of type

    参考:http://www.2cto.com/kf/201305/211728.html 错误十三 在配置拦截器后,运行的时候报错=> Error creating context 'sprin ...

  6. 开启sqlplus中执行计划

    在sqlplus中我们一般用Autotrace来查看执行计划,从而对于一些语句执行过程分析,开展优化工作.这里就演示一下如何将autotrace权限授予给普通的用户,以scott用户为例(set au ...

  7. cocos2d-js使用plist执行自身动作

    首先需要将精灵动作帧动画图片使用TexturePacker创建plist,创建好后,将生成的plist和png图片(所有帧动画图片集成的一张大图): 百牛信息技术bainiu.ltd整理发布于博客园 ...

  8. 英特尔、联发科、展讯等开始支持开源的物联网轻量化操作系统AliOS Lite

    操作系统AliOS Lite Chaos 12-21 11:03 在 12 月 20 日的云栖大会北京峰会上,阿里宣布即将开源 AliOS Lite,此前面向 IoT 领域的轻量级物联网嵌入式操作系统 ...

  9. Bootstrap-CL:字体图标(Glyphicons)

    ylbtech-Bootstrap-CL:字体图标(Glyphicons) 1.返回顶部 1. Bootstrap 字体图标(Glyphicons) 本章将讲解字体图标(Glyphicons),并通过 ...

  10. threesixty.min.js 和jquery.threesixty.js使用总结----实现360度展示

    最近公司做一个项目需要360度展示汽车的外观,就用到了threesixty.min.js,自己总结一下使用方法: treesixty.min.js 源码: /*! threesixty-slider ...