.net core模拟发送post和get请求
1年前 46,320 0
string url = "http://www.xxx.com/api/postmsg";
string jsonContent = JsonConvert.SerializeObject(message);
using (var client = new HttpClient())
{
var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
//上面代码使http Content-Type 为 application/json; charset=utf-8。如果希望Content-Type为application/json,可以使用下面两行代码
//content.Headers.Remove("Content-Type"); // "{application/json; charset=utf-8}"
//content.Headers.Add("Content-Type", "application/json");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer");
string result = client.PostAsync(url, content).Result.Content.ReadAsStringAsync().Result;
}
以上为核心代码。
https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/http-requests?view=aspnetcore-2.2
/// <summary>
/// 公共方法—— 发送http post请求 2020年6月2日11:20:42 Dennyhui
/// </summary>
/// <param name="formData">参数</param>
/// <param name="requestUri">请求地址</param>
/// <param name="token">身份验证秘钥,可为空</param>
/// <returns></returns>
public async Task<string> Client_Post(MultipartFormDataContent formData, string requestUri, string token)
{
//从工厂获取请求对象
var client = _httpClientFactory.CreateClient();
//添加请求头
if (!string.IsNullOrWhiteSpace(token))
{
client.DefaultRequestHeaders.Add("Authorization", token);
}
HttpResponseMessage response = client.PostAsync(requestUri, formData).Result;
return response.Content.ReadAsStringAsync().Result;
}
/// <summary>
/// 公共方法—— 发送http get 请求 2020年6月2日11:22:11 Dennyhui
/// <para>最终以url参数的方式提交</para>
/// </summary>
/// <param name="parameters">参数字典,可为空</param>
/// <param name="requestUri">例如/api/Files/UploadFile</param>
/// <returns></returns>
public async Task<string> Client_Get(Dictionary<string, string> parameters, string requestUri, string token)
{
//从工厂获取请求对象
var client = _httpClientFactory.CreateClient();
//添加请求头
if (!string.IsNullOrWhiteSpace(token))
{
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
}
//拼接地址
if (parameters != null)
{
var strParam = string.Join("&", parameters.Select(o => o.Key + "=" + o.Value));
requestUri = string.Concat(requestUri, '?', strParam);
}
client.BaseAddress = new Uri(requestUri);
//client.DefaultRequestHeaders.Add("Content-Type", "application/json; charset=utf-8");
return client.GetStringAsync(requestUri).Result;
}
****************************************************
此处内容传输都是用UTF-8编码
1、不带参数发送Post请求
/// <summary>
/// 指定Post地址使用Get 方式获取全部字符串
/// </summary>
/// <param name="url">请求后台地址</param>
/// <returns></returns>
public static string Post(string url)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
return result;
}
2、带参数Post请求,指定键值对
/// <summary>
/// 指定Post地址使用Get 方式获取全部字符串
/// </summary>
/// <param name="url">请求后台地址</param>
/// <returns></returns>
public static string Post(string url,Dictionary<string,string> dic)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
#region 添加Post 参数
StringBuilder builder = new StringBuilder();
int i = 0;
foreach (var item in dic)
{
if (i > 0)
builder.Append("&");
builder.AppendFormat("{0}={1}", item.Key, item.Value);
i++;
}
byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
#endregion
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取响应内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
return result;
}
3、带参数的Post请求,指定发送字符串内容
/// <summary>
/// 指定Post地址使用Get 方式获取全部字符串
/// </summary>
/// <param name="url">请求后台地址</param>
/// <param name="content">Post提交数据内容(utf-8编码的)</param>
/// <returns></returns>
public static string Post(string url, string content)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
#region 添加Post 参数
byte[] data = Encoding.UTF8.GetBytes(content);
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
#endregion
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取响应内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
return result;
}
转载方法:
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://fanyi.baidu.com/transcontent");
Encoding encoding = Encoding.UTF8;
string param = "ie=utf-8&source=txt&query=hello&t=1327829764203&token=8a7dcbacb3ed72cad9f3fb079809a127&from=auto&to=auto";
//encoding.GetBytes(postData);
byte[] bs = Encoding.ASCII.GetBytes(param);
string responseData = String.Empty;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = bs.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
reqStream.Close();
}
using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(),encoding))
{
responseData = reader.ReadToEnd().ToString();
}
context.Response.Write(responseData);
}
***************************************************************
调⽤webApi接⼝通过post⽅式传递实体参数时,发现接⼝那⾥接受不到数据,查找资料后顺利解决,顺便做下学习笔记。
⼀、json格式发送
⾸先将实体序列化为json格式的字符串,然后发送,⽰例代码 如下:
Students student =new Students("1001","张三",20,"男");
string json = JsonConvert.SerializeObject(student);
string url ="http://localhost:34626/api/values";
string result = WebHelper.HttpWebRequest(url, json, Encoding.GetEncoding("utf-8"));
其中,HttpWebRequest⽅法⽰例代码如下:
publicstaticstringHttpWebRequest(string url,string parameters, Encoding encoding,int timeout =120000)
{
var request =(HttpWebRequest)WebRequest.Create(url);
request.Timeout = timeout;
request.CookieContainer =null;
byte[] postData = encoding.GetBytes(parameters);
request.Method ="POST";
request.ContentType ="application/json";
request.ContentLength = postData.Length;
using(Stream stream = request.GetRequestStream())
{
stream.Write(postData,0, postData.Length);
}
var response =(HttpWebResponse)request.GetResponse();
string result;
using(Stream stream = response.GetResponseStream())
{
if(stream ==null)
returnstring.Empty;
using(var reader =new StreamReader(stream, encoding))
{
result = reader.ReadToEnd();
}
}
return result;
}
Post⽅法如下:
//POST api/values
publicstringPost(dynamicvalue)
{
return"value";
}
接收到Json字符串之后再反序列化即可。
结果如下图:
⼆、key/value形式发送
⾸先将实体转换为Dictionary类型,然后构造字符串发送,接⼝⽤实体接收,⽰例代码 如下:
将实体转换为
//
Dictionary<string,object>
var dic = JsonConvert.DeserializeObject<Dictionary<string,object>>(JsonConvert.SerializeObject(student));
StringBuilder builder =new StringBuilder();
foreach(var item in dic)
{
builder.AppendFormat("{0}={1}&", item.Key, item.Value);
}
string url ="http://localhost:34626/api/values";
string result = WebHelper.HttpWebRequest(url, builder.ToString(), Encoding.GetEncoding("utf-8"));
采⽤这种⽅式发送需要对HttpWebRequest⽅法修改⼀⾏代码,如下:
修改如下代码
//
request.ContentType ="application/x-www-form-urlencoded";
Post接⼝⽰例如下:
//POST api/values
publicstringPost(Students value)
{
return"value";
}
结果如下图:
虽然两种⽅式都能传递,但我还是⽐较喜欢序列化为Json格式之后发送,第⼆种⽅式对付简单的实体时⽐较好⽤,但是复杂的就不太好⽤
了。
ok
--------------------------------------------------------