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的地址,相信很 ...
随机推荐
- Visual Studio 2010 SDK
HTML 5 Intellisense for Visual Studio 2010 and 2008 Visual Studio 2010 SDK Visual Studio 2010 SP1 SD ...
- seata-server 1.3.0整合nacos,使用nacos做注册和配置中心
前言 关于seata版本的选择和更详细的安装,可以参考 SpringCloud Alibaba之Seata入门及踩坑 本篇博客是整合nacos,nacos直接下载安装解压运行就可以了. seata的下 ...
- 解密prompt系列52. 闲聊大模型还有什么值得探索的领域
在DeepSeek-R1的开源狂欢之后,感觉不少朋友都陷入了技术舒适区,但其实当前的大模型技术只是跨进了应用阶段,可以探索的领域还有不少,所以这一章咱不聊论文了,偶尔不脚踏实地,单纯仰望天空,聊聊还有 ...
- .NET 平台上的开源模型训练与推理进展
.NET 平台上的开源模型训练与推理进展 作者:痴者工良 博客:https://www.whuanle.cn 电子书仓库:https://github.com/whuanle/cs_pytorch M ...
- Lua虚拟机
Lua虚拟机概述 何为"虚拟机"? 在一门脚本语言中,总会有一个虚拟机,可是"虚拟机"是什么?简而言之,这里的"虚拟机"就是使用代码实现的用 ...
- 依赖注入的方式( 构造函数注入 、 set 方法注入 、注解注入)
一.构造函数注入 二.set方式注入 三.集合注入
- JVM 的内存区域是如何划分的?
JVM 的内存区域划分 JVM 在运行时会将内存划分为多个区域,用于管理程序运行时的不同类型数据.以下是 JVM 内存的主要划分: 1. 方法区(Method Area) 定义: 方法区是运行时数据区 ...
- Qt 官网开源最新版下载安装保姆级教程【2024-8-4 更新】
➤ 什么是Qt(了解请跳过) ➥ Qt 基本介绍 时至今日,Qt 已经经历了诸多变化.并且在未来,它也会不断地更新迭代.所以如果你想要更准确地了解 Qt,应该通过以下几种方法: ① 官方介绍 根据官方 ...
- Web客户端开发
Web开发工具 从高层次来看,可以将客户端工具放入以下三大类需要解决的问题中: 安全网络 - 在代码开发期间有用的工具. 转换 - 以某种方式转换代码的工具,例如将一种中间语言转换为浏览器可以理解的 ...
- XXL-JOB v3.0.0 | 分布式任务调度平台
Release Notes 1.[升级]调度中心升级至 SpringBoot3 + JDK17: 2.[升级]Docker镜像升级,镜像构建基于JDK17: 3.[优化]IP获取逻辑优化,优先遍历网卡 ...