This article mainly introduces the detailed explanation of network requests under c# .net core. It briefly introduces how to make http requests under .net core. The main methods are still GET and POST. Those who are interested can learn more
This article is in the VS2017 environment, .net core version 1.1 or above.
During this period, since .net core is not based on IIS, our past network request code may be incompatible and error reporting under the .net core framework. Here is a general introduction on how to make http requests under .net core. The main methods are still GET and POST. If there are any errors, please correct me!
Let’s talk about POST first. I have implemented three methods for POST. The first two are based on the same principles. There are some small differences in the latter ones, but their essence is http request. In essence, There is no difference, just the implementation method is different.
Without further ado, here’s the code:
POST asynchronous method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
public async Task<string> HttpPostAsync(string uri, string url, List<KeyValuePair<string, string>> formData = null, string charset = "UTF-8" , string mediaType = "application/x-www-form-urlencoded" )
{
string tokenUri = url;
var client = new HttpClient();
client.BaseAddress = new Uri(uri);
HttpContent content = new FormUrlEncodedContent(formData);
content.Headers.ContentType = new MediaTypeHeaderValue(mediaType);
content.Headers.ContentType.CharSet = charset;
for (int i = 0; i < formData. Count ; i++)
{
content.Headers.Add(formData[i].Key, formData[i].Value);
}
HttpResponseMessage resp = await client.PostAsync(tokenUri, content);
resp.EnsureSuccessStatusCode();
string token = await resp.Content.ReadAsStringAsync();
return token;
}
|
Copy after login
POST synchronous method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
public string HttpPost(string uri, string url, List<KeyValuePair<string, string>> formData = null, string charset = "UTF-8" , string mediaType = "application/x-www-form-urlencoded" )
{
string tokenUri = url;
var client = new HttpClient();
client.BaseAddress = new Uri(uri);
HttpContent content = new FormUrlEncodedContent(formData);
content.Headers.ContentType = new MediaTypeHeaderValue(mediaType);
content.Headers.ContentType.CharSet = charset;
for (int i = 0; i < formData. Count ; i++)
{
content.Headers.Add(formData[i].Key, formData[i].Value);
}
var res = client.PostAsync(tokenUri, content);
res.Wait();
HttpResponseMessage resp = res.Result;
var res2 = resp.Content.ReadAsStringAsync();
res2.Wait();
string token = res2.Result;
return token;
}
|
Copy after login
Unfortunately, the synchronous method is also based on asynchronous implementation. I personally think that doing so will increase system overhead. If you have other efficient implementations, please feel free to let me know!
The next step is to perform POST through the stream:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | public string Post(string url, string data, Encoding encoding, int type)
{
try
{
HttpWebRequest req = WebRequest.CreateHttp( new Uri(url));
if (type == 1)
{
req.ContentType = "application/json;charset=utf-8" ;
}
else if (type == 2)
{
req.ContentType = "application/xml;charset=utf-8" ;
}
else
{
req.ContentType = "application/x-www-form-urlencoded;charset=utf-8" ;
}
req.Method = "POST" ;
req.ContinueTimeout = 60000;
byte[] postData = encoding.GetBytes(data);
Stream reqStream = req.GetRequestStreamAsync().Result;
reqStream.Write(postData, 0, postData.Length);
reqStream.Dispose();
var rsp = (HttpWebResponse)req.GetResponseAsync().Result;
var result = GetResponseAsString(rsp, encoding);
return result;
}
catch (Exception ex)
{
throw ;
}
}
|
Copy after login
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | private string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
{
Stream stream = null;
StreamReader reader = null;
try
{
stream = rsp.GetResponseStream();
reader = new StreamReader(stream, encoding);
return reader.ReadToEnd();
}
finally
{
if (reader != null) reader.Dispose();
if (stream != null) stream.Dispose();
if (rsp != null) rsp.Dispose();
}
}
|
Copy after login
This method of POST still writes the data into the stream and performs POST. The reason why the first two key-values are written is The form is to conform to the style of Java or OC. In the webapi written in C#, since the receiving form is {=value} instead of {key=value} (determined by the nature of the webapi), I will talk about how to receive it in the webapi later. (key-value) form, appropriately avoid conflicts between .net backend personnel and android and ios, thereby achieving long-term stability in a socialist democratic society.
Next is get. Similarly, synchronous and asynchronous are all implemented by asynchronous, please read it lightly.
GET:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
public static async Task<string> HttpGetAsync(string url, List<KeyValuePair<string, string>> formData = null)
{
HttpClient httpClient = new HttpClient();
HttpContent content = new FormUrlEncodedContent(formData);
if (formData != null)
{
content.Headers.ContentType = new MediaTypeHeaderValue( "application/x-www-form-urlencoded" );
content.Headers.ContentType.CharSet = "UTF-8" ;
for (int i = 0; i < formData. Count ; i++)
{
content.Headers.Add(formData[i].Key, formData[i].Value);
}
}
var request = new HttpRequestMessage()
{
RequestUri = new Uri(url),
Method = HttpMethod.Get,
};
for (int i = 0; i < formData. Count ; i++)
{
request.Headers.Add(formData[i].Key, formData[i].Value);
}
var resp = await httpClient.SendAsync(request);
resp.EnsureSuccessStatusCode();
string token = await resp.Content.ReadAsStringAsync();
return token;
}
|
Copy after login
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
public string HttpGet(string url, List<KeyValuePair<string, string>> formData = null)
{
HttpClient httpClient = new HttpClient();
HttpContent content = new FormUrlEncodedContent(formData);
if (formData != null)
{
content.Headers.ContentType = new MediaTypeHeaderValue( "application/x-www-form-urlencoded" );
content.Headers.ContentType.CharSet = "UTF-8" ;
for (int i = 0; i < formData. Count ; i++)
{
content.Headers.Add(formData[i].Key, formData[i].Value);
}
}
var request = new HttpRequestMessage()
{
RequestUri = new Uri(url),
Method = HttpMethod.Get,
};
for (int i = 0; i < formData. Count ; i++)
{
request.Headers.Add(formData[i].Key, formData[i].Value);
}
var res = httpClient.SendAsync(request);
res.Wait();
var resp = res.Result;
Task<string> temp = resp.Content.ReadAsStringAsync();
temp.Wait();
return temp.Result;
}
|
Copy after login
【Related Recommendations】
1. .Net Core Graphical Verification Code
2. .NET Core configuration file loading and DI injection of configuration data
3. .NET Core CLI tool documentation dotnet-publish
4. Detailed introduction to ZKEACMS for .Net Core
5. Share the example code of using forms verification in .net MVC
6. Example tutorial of running ZKEACMS on CentOS
The above is the detailed content of How to make http request under .net core?. For more information, please follow other related articles on the PHP Chinese website!