目录
1.get请求方式
1.1不需要请求参数时
1.2请求参数可以用表单数据(键值对)拼接时
2.POST请求方式
2.1请求参数为json字符串格式时
2.2请求参数为表单数据(键值对)格式时
2.3请求参数为多分部数据(复合式表单)格式时,(以上传文件接口为例)
本文主要介绍了通过C#中的WebRequest来发送post和get两种请求方式的过程。
1.get请求方式
1.1不需要请求参数时
url为请求的接口地址
private string GetData(string url)
{
string result = string.Empty;
string error = string.Empty;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 20000; //超时时间
request.Method = "GET"; //请求方式
request.KeepAlive = true; //解决GetResponse操作超时问题
request.Headers.Add("Authorization", "token"); //如果接口需要鉴权, 把"token"换成自己需要的
//通过HttpWebRequest的GetResponse()方法建立HttpWebResponse,强制类型转换
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//获取响应内容,返回的数据格式: {"status":"success","msg":"成功","data":{"info": "example"}}
string postContent = new StreamReader(response.GetResponseStream()).ReadToEnd();
//结果解析,异常情况判断
JObject json = JObject.Parse(postContent);
var gList = json["data"];
if (json["status"] == null || gList == null || json["msg"] == null)
error = "接口错误";
else if (json["status"].ToString() != "success")
error = string.Format("接口查询结果返回错误,{0}", json["msg"]);
else if (gList.ToString() != string.Empty)
result = gList["info"].ToString();
else { }
}
catch (Exception ex)
{
error = ex.Message;
}
if (error != string.Empty)
MessageBox.Show(error);
return result;
}
1.2请求参数可以用表单数据(键值对)拼接时
url为请求的接口地址,pairs为请求的参数(字典格式)
private string GetUrlEncodeData(string url, Dictionary<string, string> pairs)
{
string result = string.Empty;
string error = string.Empty;
try
{
StringBuilder sb = new StringBuilder();
foreach (string key in pairs.Keys)
sb.Append(key).Append("=").Append(pairs[key]).Append("&");
if (pairs.Count > 0)
url = url + "?" + sb.ToString().Trim('&');
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded"; //表单数据(键值对)
request.Timeout = 20000; //超时时间
request.Method = "GET"; //请求方式
request.KeepAlive = true; //解决GetResponse操作超时问题
request.Headers.Add("Authorization", "token"); //如果接口需要鉴权, 把"token"换成自己需要的
//通过HttpWebRequest的GetResponse()方法建立HttpWebResponse,强制类型转换
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//获取响应内容,返回的数据格式: {"status":"success","msg":"成功","data":{"info": "example"}}
string postContent = new StreamReader(response.GetResponseStream()).ReadToEnd();
//结果解析,异常情况判断
JObject json = JObject.Parse(postContent);
var gList = json["data"];
if (json["status"] == null || gList == null || json["msg"] == null)
error = "接口错误";
else if (json["status"].ToString() != "success")
error = string.Format("接口查询结果返回错误,{0}", json["msg"]);
else if (gList.ToString() != string.Empty)
result = gList["info"].ToString();
else { }
}
catch (Exception ex)
{
error = ex.Message;
}
if (error != string.Empty)
MessageBox.Show(error);
return result;
}
2.POST请求方式
2.1请求参数为json字符串格式时
url为请求的接口地址,pairs为请求的参数(字典格式)
private string PostJsonData(string url, Dictionary<string, string> pairs)
{
string result = string.Empty;
string error = string.Empty;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 20000; //超时时间
request.Method = "POST"; //请求方式
request.KeepAlive = true; //解决GetResponse操作超时问题
request.Headers.Add("Authorization", "token"); //如果接口需要鉴权, 把"token"换成自己需要的
//设置Content-type HTTP标头的值,即请求的媒体类型
request.ContentType = "application/json"; //json字符串
//request.ContentType = "multipart/form-data"; //多分部数据
string content = JsonConvert.SerializeObject(pairs);
byte[] data = Encoding.UTF8.GetBytes(content);
//写入请求的参数
using (var stream = request.GetRequestStream())
stream.Write(data, 0, data.Length);
//通过HttpWebRequest的GetResponse()方法建立HttpWebResponse,强制类型转换
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//获取响应内容,返回的postContent是json字符串格式:{"status":"success","msg":"成功","data":{"info": "example"}}
string postContent = new StreamReader(response.GetResponseStream()).ReadToEnd();
//结果解析,异常情况判断
JObject json = JObject.Parse(postContent);
var gList = json["data"];
if (json["status"] == null || gList == null || json["msg"] == null)
error = "接口错误";
else if (json["status"].ToString() != "success")
error = string.Format("接口查询结果返回错误,{0}", json["msg"]);
else if (gList.ToString() != string.Empty)
result = gList["info"].ToString();
else { }
}
catch (Exception ex)
{
error = ex.Message;
}
if (error != string.Empty)
MessageBox.Show(error);
return result;
}
2.2请求参数为表单数据(键值对)格式时
url为请求的接口地址,pairs为请求的参数(字典格式)
private string PostUrlEncodeData(string url, Dictionary<string, string> pairs)
{
string result = string.Empty;
string error = string.Empty;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded"; //表单数据(键值对)
request.Timeout = 20000; //超时时间
request.Method = "POST"; //请求方式
request.KeepAlive = true; //解决GetResponse操作超时问题
request.Headers.Add("Authorization", "token"); //如果接口需要鉴权, 把"token"换成自己需要的
StringBuilder sb = new StringBuilder();
foreach (string key in pairs.Keys)
sb.Append(key).Append("=").Append(pairs[key]).Append("&");
string content = sb.ToString().Trim('&');
byte[] data = Encoding.UTF8.GetBytes(content);
//写入请求的参数
using (var stream = request.GetRequestStream())
stream.Write(data, 0, data.Length);
//通过HttpWebRequest的GetResponse()方法建立HttpWebResponse,强制类型转换
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//获取响应内容,返回的json字符串postContent格式:
//{"status":"success","msg":"成功","data":{"info": "example"}}
string postContent = new StreamReader(response.GetResponseStream()).ReadToEnd();
//结果解析,异常情况判断
JObject json = JObject.Parse(postContent);
var gList = json["data"];
if (json["status"] == null || gList == null || json["msg"] == null)
error = "接口错误";
else if (json["status"].ToString() != "success")
error = string.Format("接口查询结果返回错误,{0}", json["msg"]);
else if (gList.ToString() != string.Empty)
result = gList["info"].ToString();
else { }
}
catch (Exception ex)
{
error = ex.Message;
}
if (error != string.Empty)
MessageBox.Show(error);
return result;
}
2.3请求参数为多分部数据(复合式表单)格式时,(以上传文件接口为例)
url为请求的接口地址,filePath为文件的绝对路径。
首先获取本地文件路径,文章来源:https://www.toymoban.com/news/detail-400462.html
string uploadURL = "http://127.0.0.1:8888/api/test/";
string uploadFilePath = string.Empty;
OpenFileDialog openFileDialog = new OpenFileDialog
{
Filter = "所有文件|*.*"
};
if (openFileDialog.ShowDialog() == DialogResult.OK)
uploadFilePath = openFileDialog.FileName;
string result = PostMultipartData(uploadURL, uploadFilePath);
上传文件函数文章来源地址https://www.toymoban.com/news/detail-400462.html
private string PostMultipartData(string url, string filePath)
{
string result = string.Empty;
string error = string.Empty;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 20000; //超时时间
request.Method = "POST"; //请求方式
request.KeepAlive = true; //解决GetResponse操作超时问题
request.ContentType = "multipart/form-data"; //多分部数据(复合式表单)
request.Headers.Add("Authorization", "token"); //如果接口需要鉴权, 把"token"换成自己需要的
//读取文件内容
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
byte[] fileData = new byte[fs.Length];
fs.Read(fileData, 0, fileData.Length);
string fileName = Path.GetFileName(filePath);
//浏览器在发送表单的enctype="multipart/form-data", 需要在往后台发送请求的时候添加一个[boundary]属性
string boundary = "test" + DateTime.Now.Ticks.ToString("x"); // 边界符, "test"可以改, 其他部分不能改
byte[] boundarybytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n"); // 边界符开始
byte[] endbytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); // 边界符结束
//写入请求的参数
using (var stream = request.GetRequestStream())
{
//获取文件头的字节序列
string temp = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n";
string header = string.Format(temp, "file", fileName);
byte[] fileHeader = Encoding.UTF8.GetBytes(header);
stream.Write(boundarybytes, 0, boundarybytes.Length); //写入FormData项的开始边界符
stream.Write(fileHeader, 0, fileHeader.Length); //将文件头写入FormData项中
stream.Write(boundarybytes, 0, boundarybytes.Length); //每两次写入之间要加入开始边界符
stream.Write(fileData, 0, fileData.Length); //将文件流写入FormData项
stream.Write(endbytes, 0, endbytes.Length); //写入FormData的结束边界符
}
//通过HttpWebRequest的GetResponse()方法建立HttpWebResponse,强制类型转换
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//获取响应内容,返回的json字符串postContent格式:
//{"status":"success","msg":"成功","data":{"info": "example"}}
string postContent = new StreamReader(response.GetResponseStream()).ReadToEnd();
//结果解析,异常情况判断
JObject json = JObject.Parse(postContent);
var gList = json["data"];
if (json["status"] == null || gList == null || json["msg"] == null)
error = "接口错误";
else if (json["status"].ToString() != "success")
error = string.Format("接口查询结果返回错误,{0}", json["msg"]);
else if (gList.ToString() != string.Empty)
result = gList["info"].ToString();
else { }
}
catch (Exception ex)
{
error = ex.Message;
}
if (error != string.Empty)
MessageBox.Show(error);
return result;
}
到了这里,关于C# 使用WebRequest发送post和get请求的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!