C# HttpClient(包含Post和Get)
Posted 懒树懒
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# HttpClient(包含Post和Get)相关的知识,希望对你有一定的参考价值。
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace SXYC.Common public class HttpClientHelpClass /// <summary> /// get请求 /// </summary> /// <param name="url"></param> /// <returns></returns> public static string GetResponse(string url, out string statusCode) if (url.StartsWith("https")) System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = httpClient.GetAsync(url).Result; statusCode = response.StatusCode.ToString(); if (response.IsSuccessStatusCode) string result = response.Content.ReadAsStringAsync().Result; return result; return null; public static string RestfulGet(string url) HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; // Get response using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) // Get the response stream StreamReader reader = new StreamReader(response.GetResponseStream()); // Console application output return reader.ReadToEnd(); public static T GetResponse<T>(string url) where T : class, new() if (url.StartsWith("https")) System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = httpClient.GetAsync(url).Result; T result = default(T); if (response.IsSuccessStatusCode) Task<string> t = response.Content.ReadAsStringAsync(); string s = t.Result; result = JsonConvert.DeserializeObject<T>(s); return result; /// <summary> /// post请求 /// </summary> /// <param name="url"></param> /// <param name="postData">post数据</param> /// <returns></returns> public static string PostResponse(string url, string postData, out string statusCode) if (url.StartsWith("https")) System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; HttpContent httpContent = new StringContent(postData); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); httpContent.Headers.ContentType.CharSet = "utf-8"; HttpClient httpClient = new HttpClient(); //httpClient..setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8"); HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result; statusCode = response.StatusCode.ToString(); if (response.IsSuccessStatusCode) string result = response.Content.ReadAsStringAsync().Result; return result; return null; /// <summary> /// 发起post请求 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="url">url</param> /// <param name="postData">post数据</param> /// <returns></returns> public static T PostResponse<T>(string url, string postData) where T : class, new() if (url.StartsWith("https")) System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; HttpContent httpContent = new StringContent(postData); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); HttpClient httpClient = new HttpClient(); T result = default(T); HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result; if (response.IsSuccessStatusCode) Task<string> t = response.Content.ReadAsStringAsync(); string s = t.Result; result = JsonConvert.DeserializeObject<T>(s); return result; /// <summary> /// 反序列化Xml /// </summary> /// <typeparam name="T"></typeparam> /// <param name="xmlString"></param> /// <returns></returns> public static T XmlDeserialize<T>(string xmlString) where T : class, new() try XmlSerializer ser = new XmlSerializer(typeof(T)); using (StringReader reader = new StringReader(xmlString)) return (T)ser.Deserialize(reader); catch (Exception ex) throw new Exception("XmlDeserialize发生异常:xmlString:" + xmlString + "异常信息:" + ex.Message); public static string PostResponse(string url, string postData, string token, string appId, string serviceURL, out string statusCode) if (url.StartsWith("https")) System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; HttpContent httpContent = new StringContent(postData); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); httpContent.Headers.ContentType.CharSet = "utf-8"; httpContent.Headers.Add("token", token); httpContent.Headers.Add("appId", appId); httpContent.Headers.Add("serviceURL", serviceURL); HttpClient httpClient = new HttpClient(); //httpClient..setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8"); HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result; statusCode = response.StatusCode.ToString(); if (response.IsSuccessStatusCode) string result = response.Content.ReadAsStringAsync().Result; return result; return null; /// <summary> /// 修改API /// </summary> /// <param name="url"></param> /// <param name="postData"></param> /// <returns></returns> public static string KongPatchResponse(string url, string postData) var httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.ContentType = "application/x-www-form-urlencoded"; httpWebRequest.Method = "PATCH"; byte[] btBodys = Encoding.UTF8.GetBytes(postData); httpWebRequest.ContentLength = btBodys.Length; httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length); HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); var streamReader = new StreamReader(httpWebResponse.GetResponseStream()); string responseContent = streamReader.ReadToEnd(); httpWebResponse.Close(); streamReader.Close(); httpWebRequest.Abort(); httpWebResponse.Close(); return responseContent; /// <summary> /// 创建API /// </summary> /// <param name="url"></param> /// <param name="postData"></param> /// <returns></returns> public static string KongAddResponse(string url, string postData) if (url.StartsWith("https")) ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; HttpContent httpContent = new StringContent(postData); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded") CharSet = "utf-8" ; var httpClient = new HttpClient(); HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result; if (response.IsSuccessStatusCode) string result = response.Content.ReadAsStringAsync().Result; return result; return null; /// <summary> /// 删除API /// </summary> /// <param name="url"></param> /// <returns></returns> public static bool KongDeleteResponse(string url) if (url.StartsWith("https")) ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; var httpClient = new HttpClient(); HttpResponseMessage response = httpClient.DeleteAsync(url).Result; return response.IsSuccessStatusCode; /// <summary> /// 修改或者更改API /// </summary> /// <param name="url"></param> /// <param name="postData"></param> /// <returns></returns> public static string KongPutResponse(string url, string postData) if (url.StartsWith("https")) ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; HttpContent httpContent = new StringContent(postData); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded") CharSet = "utf-8" ; var httpClient = new HttpClient(); HttpResponseMessage response = httpClient.PutAsync(url, httpContent).Result; if (response.IsSuccessStatusCode) string result = response.Content.ReadAsStringAsync().Result; return result; return null; /// <summary> /// 检索API /// </summary> /// <param name="url"></param> /// <returns></returns> public static string KongSerchResponse(string url) if (url.StartsWith("https")) ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; var httpClient = new HttpClient(); HttpResponseMessage response = httpClient.GetAsync(url).Result; if (response.IsSuccessStatusCode) string result = response.Content.ReadAsStringAsync().Result; return result; return null;
.Net(C#)后台发送Get和Post请求的几种方法总结
1、通过HttpClient发送Get和Post请求
适用平台:.NET Framework 4.5+, .NET Standard 1.1+, .NET Core 1.0+
其它平台的移植版本可以通过Nuget来安装。(Nuget使用方法:http://www.cjavapy.com/article/21/)
命名空间:using System.Net.Http;
HttpClient推荐使用单一实例共享使用,发关请求的方法推荐使用异步的方式,代码如下,
private static readonly HttpClient client = new HttpClient();
//发送Get请求
var responseString = await client.GetStringAsync("http://www.example.com/recepticle.aspx");
//发送Post请求
var values = new Dictionary
{
{ "thing1", "hello" },
{ "thing2", "world" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.ywc0.com/recepticle.aspx", content);
var responseString = await response.Content.ReadAsStringAsync();
2、通过第三方类库发送Get和Post请求
1)Flurl.Http(可以通过Nuget来安装)
命名空间:using Flurl.Http;
//发送Get请求
var responseString = await "http://www.example.com/recepticle.aspx"
.GetStringAsync();
//发送Post请求
var responseString = await "http://www.example.com/recepticle.aspx"
.PostUrlEncodedAsync(new { thing1 = "hello", thing2 = "world" })
.ReceiveString();
2)RestSharp(可以通过Nuget来安装)
//发送Get和Post请求
RestClient client = new RestClient("http://ywc0.com");//指定请求的url
RestRequest req = new RestRequest("resource/{id}", Method.GET);//指定请求的方式,如果Post则改成Method.POST
request.AddParameter("name", "value"); // 添加参数到 URL querystring
request.AddUrlSegment("id", "123"); // 替换上面指定请求方式中的{id}参数
//req.AddBody(body); /*如发送post请求,则用req.AddBody()指定body内容*/
//发送请求得到请求的内容
//如果有header可以使用下面方法添加
//request.AddHeader("header", "value");
IRestResponse response = client.Execute(request);
//上传一个文件
//request.AddFile("file", path);
var content = response.Content; // 未处理的content是string
//还可以下面几种方式发送请求
//发送请求,反序列化请求结果
IRestResponse response2 = client.Execute(request);
var name = response2.Data.Name;
//发送请求下载一个文件,并保存到path路径
client.DownloadData(request).SaveAs(path);
// 简单发送异步请求
await client.ExecuteAsync(request);
// 发送异常请求并且反序列化结果
var asyncHandle = client.ExecuteAsync(request, response => {
Console.WriteLine(response.Data.Name);
});
//终止异步的请求
asyncHandle.Abort();
3、比较老一点的方法通过WebRequest发送请求
适用平台:.NET Framework 1.1+, .NET Standard 2.0+, .NET Core 1.0+
命名空间:
using System.Net;
using System.Text; // for class Encoding
using System.IO; // for StreamReader
//发送Get请求
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
//发送Post请求
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var postData = "thing1=hello";
postData += "&thing2=world";
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
4、通过WebClient的方式发送请求
适用平台:.NET Framework 1.1+, .NET Standard 2.0+, .NET Core 2.0+
命名空间:
using System.Net;
using System.Collections.Specialized;
using System.Net;
using System.Collections.Specialized;
//发送Get请求
string url = string.Format("http://localhost:28450/api/values?p1=a&p2=b");
using (var wc = new WebClient())
{
Encoding enc = Encoding.GetEncoding("UTF-8");
Byte[] pageData = wc.DownloadData(url);
string re = enc.GetString(pageData);
}
//发送Post请求
using (var client = new WebClient())
{
var values = new NameValueCollection();
values["thing1"] = "hello";
values["thing2"] = "world";
var response = client.UploadValues("http://www.ywc0.com/recepticle.aspx", values);
var responseString = Encoding.Default.GetString(response);
}
以上是关于C# HttpClient(包含Post和Get)的主要内容,如果未能解决你的问题,请参考以下文章
c# 使用HttpClient的post,get方法传输json