您的位置:首页 > 理论基础 > 计算机网络

C# HttpClientUtil 工具类 表单请求提交 附件上传下载

2018-01-02 17:20 609 查看
废话不多说,直接上干货!
以下就是常用的Post 、Delete、Get(查询用)、Put请求。
如不满足,后面还有表单提交,附件上传、下载代码。

public class HttpClientUtil
{

/// <summary>
/// post请求
/// </summary>
/// <param name="url"></param>
/// <param name="postData">post数据</param>
/// <returns></returns>
public static string PostResponse(string url, string postData)
{
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();

HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;

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 string PostResponse<T>(string url, T postData) where T : class,new()
{
string result = "0";
var format = new IsoDateTimeConverter();
format.DateTimeFormat = "yyyyMMddHHmmssSSS";
var dataJson = JsonConvert.SerializeObject(postData, Newtonsoft.Json.Formatting.Indented, format);
var content = new StringContent(dataJson, Encoding.UTF8, "application/json");
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = httpClient.PostAsync(url, content).Result;
if (response.IsSuccessStatusCode)
{
//Task<string> t = response.Content.ReadAsStringAsync();
//string s = t.Result;
//T ss = JsonConvert.DeserializeObject<T>(s);
result = "1";
}
return result;
}

/// <summary>
/// 发起post请求主键返回
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url">url</param>
/// <param name="postData">post数据</param>
/// <returns>主键</returns>
public static string PostResponseKey<T>(string url, T postData) where T : class,new()
{
string ret = "0";
var format = new IsoDateTimeConverter();
format.DateTimeFormat = "yyyyMMddHHmmssSSS";
var dataJson = JsonConvert.SerializeObject(postData, Newtonsoft.Json.Formatting.Indented, format);
var content = new StringContent(dataJson, Encoding.UTF8, "application/json");
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = httpClient.PostAsync(url, content).Result;
if (response.IsSuccessStatusCode)
{
Task<string> t = response.Content.ReadAsStringAsync();
ret = t.Result;
}
return ret;
}

/// <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 (postData != null)
//{
//    if (url.StartsWith("https"))
//        System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
//    HttpClient httpClient = new HttpClient();
//    var format = new IsoDateTimeConverter();
//    format.DateTimeFormat = "yyyyMMddHHmmssSSS";
//    var dataJson = JsonConvert.SerializeObject(postData, Newtonsoft.Json.Formatting.Indented, format);
//    var content = new StringContent(dataJson, Encoding.UTF8, "application/json");
//    HttpResponseMessage response = httpClient.PutAsync(url, content).Result;
//    if (response.IsSuccessStatusCode)
//    {
//        result = "1";
//    }
//}

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>
/// V3接口全部为Xml形式,故有此方法
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url"></param>
/// <param name="xmlString"></param>
/// <returns></returns>
public static T PostXmlResponse<T>(string url, string xmlString) where T : class,new()
{
if (url.StartsWith("https"))
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

HttpContent httpContent = new StringContent(xmlString);
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 = XmlDeserialize<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);
}

}

/// <summary>
/// get请求
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static string GetResponse(string url)
{
if (url.StartsWith("https"))
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = httpClient.GetAsync(url).Result;

if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
return result;
}
return null;
}

/// <summary>
/// get请求
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url"></param>
/// <returns></returns>
public static T GetResponse<T>(string url) where T : class,new()
{
if (url.StartsWith("https"))
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
HttpClient httpClient = new HttpClient();
httpClient.Timeout = TimeSpan.FromMilliseconds(3000);
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>
/// Get请求返回List集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url"></param>
/// <returns>List<T></returns>
public static List<T> GetResponseList<T>(string url) where T : class,new()
{
if (url.StartsWith("https"))
{
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
}
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = httpClient.GetAsync(url).Result;

List<T> result = default(List<T>);

if (response.IsSuccessStatusCode)
{
Task<string> t = response.Content.ReadAsStringAsync();
string s = t.Result;
if (s != null && !s.StartsWith("["))
{
s = "[" +s +"]";
}
result = JsonConvert.DeserializeObject<List<T>>(s);
}
return result;
}

/// <summary>
/// Delete请求
/// </summary>
/// <param name="url"></param>
/// <param name="postData">post数据</param>
/// <returns></returns>
public static string DeleteResponse(string url)
{
if (url.StartsWith("https"))
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = httpClient.DeleteAsync(url).Result;
if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
return "1";
}
return "0";
}

/// <summary>
/// 发起put请求 List格式数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url">url</param>
/// <param name="postData">put数据</param>
/// <returns></returns>
public static string PutListDataResponse<T>(string url, List<T> postData) where T : class,new()
{
string result = "0";
if (postData != null && postData.Count  > 0)
{
if (url.StartsWith("https"))
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
HttpClient httpClient = new HttpClient();
var format = new IsoDateTimeConverter();
format.DateTimeFormat = "yyyyMMddHHmmssSSS";
var dataJson = JsonConvert.SerializeObject(postData[0], Newtonsoft.Json.Formatting.Indented, format);
var content = new StringContent(dataJson, Encoding.UTF8, "application/json");

HttpResponseMessage response = httpClient.PutAsync(url, content).Result;
if (response.IsSuccessStatusCode)
{
result = "1";
}
}
else
{
HttpClient httpClient = new HttpClient();
HttpResponseMessage response =  httpClient.PutAsync(url, null).Result;
if (response.IsSuccessStatusCode)
{
result = "1";
}
}

return result;
}

/// <summary>
/// 发起put请求 (修改时候用)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url">url</param>
/// <param name="postData">put数据</param>
/// <returns></returns>
public static string PutDataResponse<T>(string url, T postData) where T : class,new()
{
string result = "0";
if (postData != null )
{
if (url.StartsWith("https"))
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
HttpClient httpClient = new HttpClient();
var format = new IsoDateTimeConverter();
format.DateTimeFormat = "yyyyMMddHHmmssSSS";
var dataJson = JsonConvert.SerializeObject(postData, Newtonsoft.Json.Formatting.Indented, format);
var content = new StringContent(dataJson, Encoding.UTF8, "application/json");
HttpResponseMessage response = httpClient.PutAsync(url, content).Result;
if (response.IsSuccessStatusCode)
{
result = "1";
}
}
else
{
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = httpClient.PutAsync(url, null).Result;
if (response.IsSuccessStatusCode)
{
result = "1";
}
}
return result;
}
}

表单提交,附件(图片举个栗子)上传、下载代码:

第一步:获取实体类,并通过反射得到键值对。

People people = new People();

people赋值。。。。。。

class GetEntityKeyValue
{
public static Dictionary<string, object> getProperties<T>(T t) where T : class // 这是参数类型约束,指定T必须是Class类型。
{
Dictionary<string, object> dic = new Dictionary<string, object>();
Type type = t.GetType();//获得该类的Type
//再用Type.GetProperties获得PropertyInfo[],然后就可以用foreach 遍历了
foreach (PropertyInfo pi in type.GetProperties())
{
object value1 = pi.GetValue(t, null);//用pi.GetValue获得值
string name = pi.Name;//获得属性的名字,后面就可以根据名字判断来进行些自己想要的操作
//进行你想要的操作
dic.Add(name,value1);
}
return dic;
}
}
  Dictionary<string, object>dic= GetEntityKeyValue.getProperties<People >(people );

第二步:上传附件,并提交表单数据

HttpClient httpClient = new HttpClient();
string url = "******************";
string filename = "******";//文件路径

using (var form = new MultipartFormDataContent())

{ string fileName = Path.GetFileNameWithoutExtension(imagePath);
var imageContent = new ByteArrayContent(ImageHelper.ImageToBytes(finishImg)); imageContent.Headers.Add("Content-Type", "multipart/form-data"); imageContent.Headers.Add("Content-Disposition", "form-data; name=\"sketch\"; filename=\"" + fileName + "\""); form.Add(imageContent, "sketch", fileName); foreach (var keyValuePair indic) { if (keyValuePair.Value != null) { form.Add(new StringContent(keyValuePair.Value.ToString()), String.Format("\"{0}\"", keyValuePair.Key)); } } var response = httpClient.PostAsync(url, form).Result; if (response.StatusCode == System.Net.HttpStatusCode.OK) { // 状态码 200 表示上传成功 } else { // 保存失败 } }
第三步:下载图片





HttpClient httpClient = new HttpClient();
HttpResponseMessage responseImg = httpClient.GetAsync(new Uri(url)).Result;
Stream streamIMg = responseImg.Content.ReadAsStreamAsync().Result;
byte[] bytes = new byte[streamIMg.Length];
streamIMg.Read(bytes, 0, bytes.Length);
// 设置当前流的位置为流的开始
streamIMg.Seek(0, SeekOrigin.Begin);
//显示图片
// ImageHelper自己写,bytes转Image
// finishImg = ImageHelper.BytesToImage(bytes);


上传的方法是参考StackOverFlow上面老外写的。其他是东拼西凑的,见笑了!

好了,这些就是几个月来的总结,希望对大家有所帮助!


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐