【C#】Http帮助类
2021-06-03 04:03
阅读:901
标签:trace https api error nbsp json concat method 方式
1、请求http帮助类
public class HttpHelper { private HttpClient _httpClient; private string _baseIPAddress; public HttpHelper(string ipaddress = "") { this._baseIPAddress = ipaddress; _httpClient = new HttpClient { BaseAddress = new Uri(_baseIPAddress) }; } ////// 创建带用户信息的请求客户端 /// /// 用户账号 /// 用户密码,当WebApi端不要求密码验证时,可传空串 /// The URI string. public HttpHelper(string userName, string pwd = "", string uriString = "") : this(uriString) { if (!string.IsNullOrEmpty(userName)) { _httpClient.DefaultRequestHeaders.Authorization = CreateBasicCredentials(userName, pwd); } } ////// 创建带用户信息的请求客户端 /// /// 用户账号 /// 用户密码,当WebApi端不要求密码验证时,可传空串 /// The URI string. private AuthenticationHeaderValue CreateBasicCredentials(string userName, string password) { string toEncode = userName + ":" + password; Encoding encoding = Encoding.GetEncoding("utf-8"); byte[] toBase64 = encoding.GetBytes(toEncode); string parameter = Convert.ToBase64String(toBase64); return new AuthenticationHeaderValue("Basic", parameter); } ////// 把请求的URL相对路径组合成绝对路径 /// private string ConcatURL(string requestUrl) { return new Uri(_httpClient.BaseAddress, requestUrl).OriginalString; } ////// Get请求数据 /// /// /// 参数字典,可为空 /// 例如/api/Files/UploadFile ///最终以url参数的方式提交 ///public string Get(Dictionary parameters, string requestUri) { if (parameters != null) { var strParam = string.Join("&", parameters.Select(o => o.Key + "=" + o.Value)); requestUri = string.Concat(ConcatURL(requestUri), "?", strParam); } else { requestUri = ConcatURL(requestUri); } var result = _httpClient.GetStringAsync(requestUri); return result.Result; } /// /// 以json的方式Post数据 返回string类型 /// /// 实体 /// 例如/api/Files/UploadFile ///最终以json的方式放置在http体中 ///public T Get (Dictionary parameters, string requestUri) where T : class { string jsonString = this.Get(parameters, requestUri); if (string.IsNullOrEmpty(jsonString)) return null; return JsonHelper.Instance.Deserialize (jsonString); } /// /// 提交字典类型的数据 /// ///最终以formurlencode的方式放置在http体中 ///System.String. public string PostDicObj(Dictionarypara, string requestUri) { Dictionary temp = new Dictionary (); foreach (var item in para) { if (item.Value != null) { if (item.Value.GetType().Name.ToLower() != "string") { temp.Add(item.Key, JsonHelper.Instance.Serialize(item.Value)); } else { temp.Add(item.Key, item.Value.ToString()); } } else { temp.Add(item.Key, ""); } } return PostDic(temp, requestUri); } /// /// Post Dic数据 /// ///最终以formurlencode的方式放置在http体中 ///System.String. public string PostDic(Dictionarytemp, string requestUri) { HttpContent httpContent = new FormUrlEncodedContent(temp); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); return Post(requestUri, httpContent); } /// /// byte数据 /// /// /// ///public string PostByte(byte[] bytes, string requestUrl) { HttpContent content = new ByteArrayContent(bytes); content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); return Post(requestUrl, content); } /// /// 以json的方式Post数据 返回string类型 /// /// 实体 /// 例如/api/Files/UploadFile ///最终以json的方式放置在http体中 ///public string Post(object obj, string requestUri) { string request = string.Empty; if (obj != null) request = JsonHelper.Instance.Serialize(obj); HttpContent httpContent = new StringContent(request); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); return Post(requestUri, httpContent); } public string Post(string requestUri, HttpContent content) { var result = _httpClient.PostAsync(requestUri, content); return result.Result.Content.ReadAsStringAsync().Result; } public string PostDic(Dictionary temp, string requestUri,Action action) { try { HttpContent httpContent = new FormUrlEncodedContent(temp); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); return Post(requestUri, httpContent); } catch (Exception ex) { action(ex.Message + ",堆栈信息:" + ex.StackTrace); } return string.Empty; } public string HttpPost(string url, string body, Action action) { try { string contenttype = "application/x-www-form-urlencoded"; HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.Method = "POST"; httpWebRequest.ContentType = contenttype; byte[] btBodys = Encoding.UTF8.GetBytes(body); httpWebRequest.ContentLength = btBodys.Length; using (Stream newStream = httpWebRequest.GetRequestStream()) { // Send data. newStream.Write(btBodys, 0, btBodys.Length); } // Get response HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); StreamReader reader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8); string result = reader.ReadToEnd();//得到结果 reader.Close(); httpWebResponse.Close(); httpWebRequest.Abort(); return result; } catch (Exception ex) { action(ex.Message+",堆栈信息:"+ex.StackTrace); } return string.Empty; } public static string HttpGet(string url, string httpToken,ref string message,DateTime IfModifiedSince = default(DateTime), Dictionary headers = null) { try { HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url); wbRequest.Method = "GET"; wbRequest.Headers.Add("Authorization", httpToken); if (IfModifiedSince != null && IfModifiedSince != default(DateTime)) { wbRequest.IfModifiedSince = IfModifiedSince; } if (headers != null) { foreach (var item in headers) { wbRequest.Headers.Add(item.Key, item.Value); } } HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse(); using (Stream responseStream = wbResponse.GetResponseStream()) { using (StreamReader sReader = new StreamReader(responseStream)) { return sReader.ReadToEnd(); } } } catch (Exception ex) { message = ex.Message + ",堆栈信息:" + ex.StackTrace; return string.Empty; } } }
2、如果是https需要判断,将https请求服务器证书为ture并设置安全协议类型
ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
【C#】Http帮助类
标签:trace https api error nbsp json concat method 方式
原文地址:https://www.cnblogs.com/Seven77yixuan/p/10915404.html
上一篇:C# PagedList 真分页
下一篇:【C#】通用辅助方法
评论
亲,登录后才可以留言!