从调用API接口 看.net framework和 net core的异同
答案:1 悬赏:30 手机版
解决时间 2021-11-15 14:01
- 提问者网友:贪了杯
- 2021-11-15 02:44
从调用API接口 看.net framework和 net core的异同
最佳答案
- 五星知识达人网友:woshuo
- 2021-11-15 03:19
由于.net core是跨平台使用的,所有微软重写好多API,由此有些差异也是正常的。
现在就来看下请求API的差别吧。
首先,原本的.net framework请求方法:
复制代码
public static T HttpPostWithDecompression(string request, string url, int timeout) where T : new()
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Proxy = null;
httpWebRequest.Timeout = timeout;
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/json";
httpWebRequest.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
var bytes = Encoding.UTF8.GetBytes(request);
Stream requestStream = null;
var responseContent = string.Empty;
try
{
requestStream = httpWebRequest.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
var webResponse = httpWebRequest.GetResponse();
var stream = webResponse.GetResponseStream();
if (stream != null)
{
var streamReader = new StreamReader(stream);
responseContent = streamReader.ReadToEnd();
streamReader.Close();
}
webResponse.Close();
return JsonConvert.DeserializeObject(responseContent);
}
catch (Exception exception)
{
return new T();
}
finally
{
if (requestStream != null)
{
requestStream.Close();
}
}
}
复制代码
第一种返回错误编码的.net core的写法:
复制代码
public async static Task HttpPostWithDecompression(string request, string url, int timeout) where T : new()
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Proxy = null;
httpWebRequest.ContinueTimeout = timeout;
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers["Accept-Encoding"] = "gzip,deflate";
//httpWebRequest.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
var data = Encoding.UTF8.GetBytes(request);
using (var requestStream = await httpWebRequest.GetRequestStreamAsync())//释放
{
requestStream.Write(data, 0, data.Length);
}
string result = string.Empty;
//响应流
using (var response = (HttpWebResponse)await httpWebRequest.GetResponseAsync())
{
Stream responseStream = null;
if (response.StatusCode == HttpStatusCode.OK)
{
responseStream = response.GetResponseStream();
if (responseStream != null)
{
var streamReader = new StreamReader(responseStream, Encoding.UTF8);
//获取返回的信息
result = streamReader.ReadToEnd();
return JsonConvert.DeserializeObject(result);
}
}
}
return new T();
}
复制代码
查看下.net core下的属性和方法:
可以明显发现比.net framwork下少了好多。
也就是.net core的请求类型,更趋于向浏览器的请求头靠拢,也就是使用Headers字典(.net framwork下也有,但是同层级也会有一些属性,比如采用压缩)。
主要的区别就是 响应流 采用的是异步的方式,而.net framwork采用同步的方式,必须手动close(),而新的写法,就只能用using了。
但是,上述的这个方法,害死人了,请求也成功,就是编码始终调试不对,请求各位大神指点一二。
由于水平问题,未能解决上述问题,所以小弟采用.net core的 HttpClientHandler 类进行http请求:
get方法
复制代码
///
/// get请求
///
/// url包含参数
public static async Task doGet(string url) where T : new()
{
var handler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.GZip
};
using (var http = new HttpClient(handler))
{
var response = await http.GetAsync(url);
//确保HTTP成功状态值
response.EnsureSuccessStatusCode();
string responseStr =response.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject(responseStr);
}
}
复制代码
post请求
复制代码
///
/// post请求
///
/// url包含参数
public async static Task HttpPostWithDecompression(string request, string apiUrl, int timeout) where T : new()
{
HttpClientHandler handler = new HttpClientHandler();
handler.Proxy = null;
handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
var data = Encoding.UTF8.GetBytes(request);
using (var httpClient = new HttpClient(handler))
{
httpClient.BaseAddress = new Uri(apiUrl);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var cont = new StringContent(request);
//var content = new FormUrlEncodedContent(JsonConvert.DeserializeObject>(request));
//被上面这个注释掉的代码,这种偷懒转Dic的方式给坑苦了,不能这么用啊!!!
var response = await httpClient.PostAsync(apiUrl, cont);
string result = response.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject(result);
}
}
现在就来看下请求API的差别吧。
首先,原本的.net framework请求方法:
复制代码
public static T HttpPostWithDecompression
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Proxy = null;
httpWebRequest.Timeout = timeout;
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/json";
httpWebRequest.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
var bytes = Encoding.UTF8.GetBytes(request);
Stream requestStream = null;
var responseContent = string.Empty;
try
{
requestStream = httpWebRequest.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
var webResponse = httpWebRequest.GetResponse();
var stream = webResponse.GetResponseStream();
if (stream != null)
{
var streamReader = new StreamReader(stream);
responseContent = streamReader.ReadToEnd();
streamReader.Close();
}
webResponse.Close();
return JsonConvert.DeserializeObject
}
catch (Exception exception)
{
return new T();
}
finally
{
if (requestStream != null)
{
requestStream.Close();
}
}
}
复制代码
第一种返回错误编码的.net core的写法:
复制代码
public async static Task
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Proxy = null;
httpWebRequest.ContinueTimeout = timeout;
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers["Accept-Encoding"] = "gzip,deflate";
//httpWebRequest.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
var data = Encoding.UTF8.GetBytes(request);
using (var requestStream = await httpWebRequest.GetRequestStreamAsync())//释放
{
requestStream.Write(data, 0, data.Length);
}
string result = string.Empty;
//响应流
using (var response = (HttpWebResponse)await httpWebRequest.GetResponseAsync())
{
Stream responseStream = null;
if (response.StatusCode == HttpStatusCode.OK)
{
responseStream = response.GetResponseStream();
if (responseStream != null)
{
var streamReader = new StreamReader(responseStream, Encoding.UTF8);
//获取返回的信息
result = streamReader.ReadToEnd();
return JsonConvert.DeserializeObject
}
}
}
return new T();
}
复制代码
查看下.net core下的属性和方法:
可以明显发现比.net framwork下少了好多。
也就是.net core的请求类型,更趋于向浏览器的请求头靠拢,也就是使用Headers字典(.net framwork下也有,但是同层级也会有一些属性,比如采用压缩)。
主要的区别就是 响应流 采用的是异步的方式,而.net framwork采用同步的方式,必须手动close(),而新的写法,就只能用using了。
但是,上述的这个方法,害死人了,请求也成功,就是编码始终调试不对,请求各位大神指点一二。
由于水平问题,未能解决上述问题,所以小弟采用.net core的 HttpClientHandler 类进行http请求:
get方法
复制代码
///
/// get请求
///
/// url包含参数
public static async Task
{
var handler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.GZip
};
using (var http = new HttpClient(handler))
{
var response = await http.GetAsync(url);
//确保HTTP成功状态值
response.EnsureSuccessStatusCode();
string responseStr =response.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject
}
}
复制代码
post请求
复制代码
///
/// post请求
///
/// url包含参数
public async static Task
{
HttpClientHandler handler = new HttpClientHandler();
handler.Proxy = null;
handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
var data = Encoding.UTF8.GetBytes(request);
using (var httpClient = new HttpClient(handler))
{
httpClient.BaseAddress = new Uri(apiUrl);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var cont = new StringContent(request);
//var content = new FormUrlEncodedContent(JsonConvert.DeserializeObject
//被上面这个注释掉的代码,这种偷懒转Dic的方式给坑苦了,不能这么用啊!!!
var response = await httpClient.PostAsync(apiUrl, cont);
string result = response.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject
}
}
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯