基础学习

/// <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. Your Firefox profile cannot be loaded. It may be missing or inaccessible

    ubuntu下出现打开frefox出现Your Firefox profile cannot be loaded. It may be missing or inaccessible 1:用命令行输入 ...

  2. [RK3288]PMU配置(RK808)【转】

    本文转载自:http://www.javashuo.com/content/p-6398007.html 硬件原理 pmic 电路原理 平台概述 RK808 PWM 介绍 驱动分析 dts 驱动流程 ...

  3. 树状数组(二叉索引树 BIT Fenwick树) *【一维基础模板】(查询区间和+修改更新)

    刘汝佳:<训练指南>Page(194) #include <stdio.h> #include <string.h> #include <stdlib.h&g ...

  4. hdu 1711 Number Sequence 解题报告

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1711 题目意思:给出一条有n个数的序列a[1],a[2],......,a[n],和一条有m 个数的序 ...

  5. hdu 4268 Alice and Bob(贪心+multiset)

    题意:卡牌覆盖,每张卡牌有高(height)和宽(width).求alice的卡牌最多可以覆盖多少bob的卡牌 思路:贪心方法就是找h可以覆盖的条件下找w最大的去覆盖. #include<ios ...

  6. golang defer使用——资源关闭时候多用

    defer Go语言中有种不错的设计,即延迟(defer)语句,你可以在函数中添加多个defer语句.当函数执行到最后时,这些defer语句会按照逆序执行,最后该函数返回.特别是当你在进行一些打开资源 ...

  7. UIFont 字体样式 [UIFont fontWithName~];

    设置字体样式代码:[UIFont fontWithName:@"Arial-BoldMT" size:15] 下边一一列举: 一:Font Family: American Typ ...

  8. [Selenium] 操作新弹出窗口之验证标题和内容

    1)验证标题 package com.learningselenium.normalwebdriver; import static org.junit.Assert.*; import java.u ...

  9. Map集合的几种遍历方式

    Map<String ,String> map=new HashMap<String,String>(); map.put("1","value1 ...

  10. [yii2]Module的Namespace和控制器位置

    namespace和目录对应,否则无法找到控制器类,module文件在根路径 使用gii生成Module为\app\admin,那么 namespace app; class admin extend ...