基础学习

/// <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);

使用示例

最新文章

  1. LBS上传到百度地图
  2. linux安装jdk 不成功,找不到版本问题
  3. JMS的可靠性
  4. (六)、nodejs中的express框架获取http参数
  5. OracleL
  6. 窗体控件 回车事件 分类: WinForm 2014-11-21 10:45 233人阅读 评论(0) 收藏
  7. Day14 html简介
  8. HDOJ的题目分类
  9. 在多个Activity中回传值(startActivityForResult())
  10. ES6 快速入门
  11. Android Studio 调试各种国产手机经验总结
  12. Java Callable接口、Runable接口、Future接口
  13. windows乱码
  14. 起床困难综合症 NOI_2014_D1T1
  15. 关于JBoss日志中的报错Exception in thread &quot;AWT-EventQueue-0&quot;的解决记录
  16. python 3安装PDFMiner3K
  17. Qt 信号槽传递自定义结构体
  18. 前端开发之HTML篇一
  19. kafka 自启脚本
  20. vue-cli中的ESlint配置文件eslintrc.js详解

热门文章

  1. virtualbox创建centos7虚拟机
  2. Mac开发必备工具(一)—— Homebrew
  3. ossfs常见配置错误
  4. linux初级学习笔记九:linux I/O管理,重定向及管道!(视频序号:04_3)
  5. html5--6-11 CSS选择器7--伪类选择器
  6. [Selenium] Selenium WebDriver 的下载和安装
  7. bzoj 5072 小A的树 —— 树形DP
  8. UI:数据库练习、滤镜效果
  9. java链接sqlserver数据库
  10. (二十六)分类信息的curd-分类信息添加