C#操作HttpClient工具类库
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
using Newtonsoft.Json;
namespace Dcflow
{
public class HttpHelper
{
//获取Configuration对象
public static string DCFLOW_ZUUL = ConfigurationManager.AppSettings["SERVER_URL"];
//token键
public static string ACCESS_TOKEN_KEY = "";
//token值
public static string ACCESS_TOKEN_VALUE = "";
private static Dictionary<string, string> headers;
public static Dictionary<string, string> Headers { get => headers; set => headers = value; }
private static readonly HttpClient _httpClient;
static HttpHelper()
{
try
{
//HttpClient热身
_httpClient = new HttpClient() { BaseAddress = new Uri(DCFLOW_ZUUL) };
_httpClient.DefaultRequestHeaders.Connection.Add("keep-alive");
_httpClient.SendAsync(new HttpRequestMessage
{
Method = new HttpMethod("HEAD"),
RequestUri = new Uri(DCFLOW_ZUUL + "/")
}).Result.EnsureSuccessStatusCode();
}
catch (Exception)
{
}
}
public static String httpGet(string url)
{
if (HttpHelper.headers != null)
{
_httpClient.DefaultRequestHeaders.Clear();
headers[ACCESS_TOKEN_KEY] = HttpHelper.ACCESS_TOKEN_VALUE;
// 设置请求头
foreach (KeyValuePair<string, string> item in headers)
{
_httpClient.DefaultRequestHeaders.Add(item.Key, item.Value);
}
}
var data = "";
try
{
// response
var response = _httpClient.GetAsync(new Uri(DCFLOW_ZUUL + url)).Result;
data = response.Content.ReadAsStringAsync().Result;
}
catch (Exception e)
{
MessageBox.Show("HTTP GET请求失败,请检查网络或联系管理员查看服务器状态,错误消息:" + e.Message);
//throw;
}
return data;//接口调用成功获取的数据
}
public static String httpPost(string url, Dictionary<string, string> param, string dataType)
{
if (HttpHelper.headers != null)
{
_httpClient.DefaultRequestHeaders.Clear();
headers[ACCESS_TOKEN_KEY] = HttpHelper.ACCESS_TOKEN_VALUE;
//设置请求头
foreach (KeyValuePair<string, string> item in headers)
{
_httpClient.DefaultRequestHeaders.Add(item.Key, item.Value);
}
}
var data = "";
try
{
ByteArrayContent content = null;
if (dataType.ToLower().Equals("json"))
{
content = new StringContent(JsonConvert.SerializeObject(param));
//设置Http的内容标头
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
}
else
{
content = new FormUrlEncodedContent(param);
}
// response
var response = _httpClient.PostAsync(DCFLOW_ZUUL + url, content).Result;
data = response.Content.ReadAsStringAsync().Result;
}
catch (Exception e)
{
MessageBox.Show("HTTP POST请求失败,请检查网络或联系管理员查看服务器状态,错误消息:" + e.Message);
//throw;
}
return data;//接口调用成功数据
}
public static String httpUploadAsync(string url, List<string> filePath)
{
var data = "";
try
{
using (var content = new MultipartFormDataContent())
{
for (int i = 0; i < filePath.Count; i++)
{
FileStream fs = File.OpenRead(filePath[i]);
var streamContent = new StreamContent(fs);
var imageContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);
content.Add(imageContent, "upfile", Path.GetFileName(filePath[i]));
fs.Close();
}
// response
var response = _httpClient.PostAsync(DCFLOW_ZUUL + url, content).Result;
data = response.Content.ReadAsStringAsync().Result;
};
}
catch (Exception e)
{
MessageBox.Show("HTTP POST MultipartFormData 请求失败,请检查网络或联系管理员查看服务器状态,错误消息:" + e.Message);
//throw;
}
return data;
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
2018-02-06 一个IT青年北漂四年的感悟
2018-02-06 一个IT青年北漂四年的感悟
2018-02-06 一个IT青年北漂四年的感悟
2017-02-06 ASP.NET C# List分页