废话不多说,直接上干货!
以下就是常用的Post 、Delete、Get(查询用)、Put请求。
如不满足,后面还有表单提交,附件上传、下载代码。
public class HttpClientUtil
{
///
/// post请求
///
///
/// post数据
///
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;
}
///
/// 发起post请求
///
///
/// url
/// post数据
///
public static string PostResponse(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 t = response.Content.ReadAsStringAsync();
//string s = t.Result;
//T ss = JsonConvert.DeserializeObject(s);
result = "1";
}
return result;
}
///
/// 发起post请求主键返回
///
///
/// url
/// post数据
/// 主键
public static string PostResponseKey(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 t = response.Content.ReadAsStringAsync();
ret = t.Result;
}
return ret;
}
///
/// 发起post请求
///
///
/// url
/// post数据
///
public static T PostResponse(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 t = response.Content.ReadAsStringAsync();
string s = t.Result;
result = JsonConvert.DeserializeObject(s);
}
return result;
}
///
/// V3接口全部为Xml形式,故有此方法
///
///
///
///
///
public static T PostXmlResponse(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 t = response.Content.ReadAsStringAsync();
string s = t.Result;
result = XmlDeserialize(s);
}
return result;
}
///
/// 反序列化Xml
///
///
///
///
public static T XmlDeserialize(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);
}
}
///
/// get请求
///
///
///
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;
}
///
/// get请求
///
///
///
///
public static T GetResponse(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 t = response.Content.ReadAsStringAsync();
string s = t.Result;
result = JsonConvert.DeserializeObject(s);
}
return result;
}
///
/// Get请求返回List集合
///
///
///
/// List
public static List GetResponseList(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 result = default(List);
if (response.IsSuccessStatusCode)
{
Task t = response.Content.ReadAsStringAsync();
string s = t.Result;
if (s != null && !s.StartsWith("["))
{
s = "[" +s +"]";
}
result = JsonConvert.DeserializeObject>(s);
}
return result;
}
///
/// Delete请求
///
///
/// post数据
///
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";
}
///
/// 发起put请求 List格式数据
///
///
/// url
/// put数据
///
public static string PutListDataResponse(string url, List 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;
}
///
/// 发起put请求 (修改时候用)
///
///
/// url
/// put数据
///
public static string PutDataResponse(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 getProperties(T t) where T : class // 这是参数类型约束,指定T必须是Class类型。
{
Dictionary dic = new Dictionary();
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第二步:上传附件,并提交表单数据
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上面老外写的。其他是东拼西凑的,见笑了!
好了,这些就是几个月来的总结,希望对大家有所帮助!