C# HttpClientHelper
public class HttpClientHelper
{ /// <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; } using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using (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; }
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using (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>
/// GET请求
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static string GetResponse(string url)
{
if (url.StartsWith("https"))
{ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; } using (HttpClient httpClient = new HttpClient())
{
using (HttpResponseMessage response = httpClient.GetAsync(url).Result)
{
if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
return result;
}
return null;
}
}
} /// <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; }
using (HttpContent httpContent = new StringContent(postData))
{
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
httpContent.Headers.ContentType.CharSet = "utf-8";
using (HttpClient httpClient = new HttpClient())
{
using (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; }
using (HttpContent httpContent = new StringContent(postData))
{
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
using (HttpClient httpClient = new HttpClient())
{
T result = default(T);
using (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;
}
}
}
} 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; } using (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);
using (HttpClient httpClient = new HttpClient())
{
using (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>
/// 修改请求
/// </summary>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <returns></returns>
public static string PatchResponse(string url, string postData)
{ HttpWebRequest 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); using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
{
string responseContent = streamReader.ReadToEnd();
httpWebResponse.Close();
streamReader.Close();
httpWebRequest.Abort();
httpWebResponse.Close();
return responseContent;
}
}
} /// <summary>
/// 创建Form表单API请求
/// </summary>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <returns></returns>
public static string CreateFormResponse(string url, string postData)
{
if (url.StartsWith("https")) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; } using (HttpContent httpContent = new StringContent(postData))
{
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded") { CharSet = "utf-8" };
using (HttpClient httpClient = new HttpClient())
{
using (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 DeleteResponse(string url)
{
if (url.StartsWith("https")) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; }
using (HttpClient httpClient = new HttpClient())
{
using (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 PutResponse(string url, string postData)
{
if (url.StartsWith("https")) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; } using (HttpContent httpContent = new StringContent(postData))
{
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded") { CharSet = "utf-8" };
using (HttpClient httpClient = new HttpClient())
{
using (HttpResponseMessage response = httpClient.PutAsync(url, httpContent).Result)
{
if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
return result;
}
return null;
}
}
}
} }
C# HttpClientHelper的更多相关文章
- C#微信开发之旅(二):基础类之HttpClientHelper(更新:SSL安全策略)
public class HttpClientHelper 2 { 3 /// <summary> 4 /// get请求 5 ...
- C# HttpClientHelper请求
public class HttpClientHelper { /// <summary> /// get请求 /// </summary> /// <param nam ...
- java HttpClientHelper
1 首先配置pom.xml,具体参考我的这篇文章:使用httpclient需要的maven依赖 2 上代码 import java.io.IOException; import java.io.Inp ...
- HttpClientHelper
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System ...
- 使用HttpClient的优解
新工作入职不满半周,目前仍然还在交接工作,适应环境当中,笔者不得不说看别人的源码实在是令人痛苦.所幸今天终于将大部分工作流畅地看了一遍,接下来就是熟悉框架技术的阶段了. 也正是在看源码的过程当中,有一 ...
- 又一种XML的解析方法
[Fact(DisplayName="用户名为空")] public void Should_UsernameEmpty() { var paras = new Dictionar ...
- windows phone 8.1教务在线客户端(后续)
经过了一番折腾,这个wp教务在线算是告一段落了,其实原理很简单,就是post方式访问登陆页面返回cookie,然后带着这个cookie用get方式继续访问你想要访问并取回内容的页面,而且httpcli ...
- WebApi 登录身份验证
前言:Web 用户的身份验证,及页面操作权限验证是B/S系统的基础功能,一个功能复杂的业务应用系统,通过角色授权来控制用户访问,本文通过Form认证,Mvc的Controller基类及Action的权 ...
- RESTLET开发实例
1 前提 由于近期工作的需要,要把RESTLET应用到项目中,于是在网上参考了一些资料的基础上,实践了一个关于RESTLET接口的小例子. Restlet的思想是:HTTP客户端与HTTP服务器之间的 ...
- android httpClient 支持HTTPS的2种处理方式
摘自: http://www.kankanews.com/ICkengine/archives/9634.shtml 项目中Android https或http请求地址重定向为HTTPS的地址,相信很 ...
随机推荐
- DevOps系列——Gitlab私服
Gitlab/GitHub是两兄弟,但GitHub本着共享技术的精神,私有库是要钱滴,而且代码放别人家里,晚上总是有点睡不踏实, 来个代码泄露或者突然被区别对待,比如GitHub断供来自伊朗.叙利亚的 ...
- 理解PostgreSQL和SQL Server中的文本数据类型
理解PostgreSQL和SQL Server中的文本数据类型 在使用PostgreSQL时,理解其文本数据类型至关重要,尤其对有SQL Server背景的用户而言.尽管两个数据库系统都支持文本存储, ...
- idea插件开发踩坑记录
问题 build.gradles.kts配置文件中全部爆红,提示Cannot access script base class 'org.gradle.kotlin.dsl.KotlinBuildSc ...
- Flowable快速入门
flowable官方文档 官网:https://tkjohn.github.io/flowable-userguide/#_getting_started 工作流(Workflow),是& ...
- JDK1.8的ConcurrentHashMap的put方法源码
一.JDK1.8的ConcurrentHashMap的put方法源码 ConcurrentHashMap 是 Java 并发包(java.util.concurrent)中的一个高性能线程安全哈希表实 ...
- eolinker请求预处理:配置全局环境变量后,步骤内去掉请求头信息
特别注意:需要使用全局变量或者预处理前务必阅读本链接https://www.cnblogs.com/becks/p/13713278.html 1.描述,用例配置环境变量后会在请求前自动加上域名和请求 ...
- 小模型工具调用能力激活:以Qwen2.5 0.5B为例的Prompt工程实践
在之前的分析中,我们深入探讨了cline prompt的设计理念(Cline技术分析:prompt如何驱动大模型对本地文件实现自主变更),揭示了其在激发语言模型能力方面的潜力.现在,我们将这些理论付诸 ...
- Java编程--设计模式之装饰者模式
目录 装饰者模式 简介 做馒头实例 生产汽车实例 常见使用 装饰者模式 简介 装饰者模式的主要功能就是对一个类的功能进行扩充! 对于需要对某个类扩充,但是该类是final类,不能被继承,这是时候可以用 ...
- Axure RP医疗在线挂号问诊原型图医院APP原形模板
Axure RP医疗在线挂号问诊原型图医院APP原形模板 医疗在线挂号问诊Axure RP原型图医院APP原形模板,是一款原创的医疗类APP,设计尺寸采用iPhone13(375*812px),原型图 ...
- 《OKR》| 聚焦小目标, 成就大梦想
今天想和大家分享的书籍是 <每个人的 OKR>. 恰好我司也是采用 OKR 结合 KPI 的方式进行目标和绩效管理, 在实践中通过放大目标的功能, 缩小行动的自由, 聚焦在单一方向的机制, ...