HttpwebClient的四种请求方式
最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来。
十年河东十年河西,莫欺少年穷。
本文旨在发布代码,供自己参考,也供大家参考,谢谢。
正题:
HttpWebClient的四种请求方式:Get、Post、Put、Delete
系列代码如下:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel;
using System.Web; namespace WebApiTest
{
/// <summary>
/// 系列代码整理:陈卧龙 18137070152 QQ 1429677330
/// </summary>
public class RestServiceProxy
{
#region static List<T> Get<T>(string endpoint)类型请求
/// <summary>
/// HttpClientGet请求
/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <param name="endpoint">URL</param>
/// <returns></returns>
public static List<T> Get<T>(string endpoint)
{
using (var httpClient = NewHttpClient())
{
httpClient.DefaultRequestHeaders.Add("mac", GlobalClientConfig.MacAddress);//带上请求标题头
var response = httpClient.GetAsync(endpoint).Result;
return JsonConvert.DeserializeObject<List<T>>(response.Content.ReadAsStringAsync().Result);
}
}
#endregion #region static T Get<T>(int id, string endpoint)类型请求
public static T Get<T>(int id, string endpoint)
{
using (var httpClient = NewHttpClient())
{
httpClient.DefaultRequestHeaders.Add("mac", GlobalClientConfig.MacAddress);
//httpClient.DefaultRequestHeaders.Add("marketcode", GlobalClientConfig.MarketCode);//新宇多带的标题头
//httpClient.DefaultRequestHeaders.Add("languagecode", GlobalClientConfig.LanguageResource);
var response = httpClient.GetAsync(endpoint + id).Result;
if (response.StatusCode != HttpStatusCode.OK)
{
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
throw new UnauthorizedAccessException();
}
else
{
throw new Exception("Invoke Server Service Error");
}
} return JsonConvert.DeserializeObject<T>(response.Content.ReadAsStringAsync().Result);
}
}
public static T Get<T>(string id, string endpoint)
{
T obj;
using (var httpClient = NewHttpClient())
{
httpClient.DefaultRequestHeaders.Add("mac", GlobalClientConfig.MacAddress); var response = httpClient.GetAsync(endpoint + id).Result;
if (response.StatusCode != HttpStatusCode.OK)
{
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
throw new UnauthorizedAccessException();
}
else
{
throw new Exception("Invoke Server Service Error");
}
} string result = response.Content.ReadAsStringAsync().Result;
obj = JsonConvert.DeserializeObject<T>(result);
return obj;
}
}
#endregion #region Get请求、传递一个对象,返回对象或对象集static T1 Get<T1, T2>(T2 data, string endpoint)
/// <summary>
/// general get restful service data
/// </summary>
/// <typeparam name="T1">return data type 返回值类型</typeparam>
/// <typeparam name="T2">input data type 参数类型</typeparam>
/// <param name="data">search condition</param>
/// <param name="endpoint">service url 请求URI</param>
/// <returns></returns>
public static T1 Get<T1, T2>(T2 data, string endpoint)
{
using (var httpClient = NewHttpClient())
{
httpClient.DefaultRequestHeaders.Add("mac", GlobalClientConfig.MacAddress); var _endpoint = endpoint; var requestMessage = GetObjectPropertyValue(data);
if (!string.IsNullOrEmpty(requestMessage))
{
_endpoint += "?" + requestMessage.Remove(, );
}
var response = httpClient.GetAsync(_endpoint).Result;
if (response.StatusCode != HttpStatusCode.OK)
{
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
throw new UnauthorizedAccessException();
}
else
{
throw new Exception("Invoke Server Service Error");
}
} string result = response.Content.ReadAsStringAsync().Result;
return JsonHelper.JsonDeserialize<T1>(result);
}
} public static List<T1> GetList<T1, T2>(T2 data, string endpoint)
{
using (var httpClient = NewHttpClient())
{
httpClient.DefaultRequestHeaders.Add("mac", GlobalClientConfig.MacAddress); var _endpoint = endpoint;
var requestMessage = GetObjectPropertyValue(data);
if (!string.IsNullOrEmpty(requestMessage))
{
_endpoint += "?" + requestMessage.Remove(, );
}
var response = httpClient.GetAsync(_endpoint).Result;
if (response.StatusCode != HttpStatusCode.OK)
{
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
throw new UnauthorizedAccessException();
}
else
{
throw new Exception("Invoke Server Service Error");
}
}
string result = response.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<List<T1>>(result);
}
}
#endregion #region Get请求 不/传递Id 返回对象集合
public static List<T1> GetList<T1>(string id, string endpoint)
{
using (var httpClient = NewHttpClient())
{
httpClient.DefaultRequestHeaders.Add("mac", GlobalClientConfig.MacAddress); var response = httpClient.GetAsync(endpoint + id).Result;
if (response.StatusCode != HttpStatusCode.OK)
{
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
throw new UnauthorizedAccessException();
}
else
{
throw new Exception("Invoke Server Service Error");
}
} string result = response.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<List<T1>>(result);
}
} public static List<T1> GetList<T1>(string endpoint)
{
using (var httpClient = NewHttpClient())
{
httpClient.DefaultRequestHeaders.Add("mac", GlobalClientConfig.MacAddress); var response = httpClient.GetAsync(endpoint).Result;
if (response.StatusCode != HttpStatusCode.OK)
{
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
throw new UnauthorizedAccessException();
}
else
{
throw new Exception("Invoke Server Service Error");
}
} string result = response.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<List<T1>>(result);
}
}
#endregion #region Post请求 static string Post<T>(T data, string endpoint)及 static TRetrun Post<TRetrun, TPost>(TPost data, string endpoint)
public static string Post<T>(T data, string endpoint)
{
using (var httpClient = NewHttpClient())
{
httpClient.DefaultRequestHeaders.Add("mac", GlobalClientConfig.MacAddress); var requestMessage = JsonHelper.JsonSerializer<T>(data);
HttpContent contentPost = new StringContent(requestMessage, Encoding.UTF8, "application/json");
var response = httpClient.PostAsync(endpoint, contentPost).Result;
if (response.StatusCode != HttpStatusCode.OK)
{
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
throw new UnauthorizedAccessException();
}
else
{
throw new Exception("Invoke Server Service Error");
}
} string result = response.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<string>(result); }
} public static TRetrun Post<TRetrun, TPost>(TPost data, string endpoint)
{
using (var httpClient = NewHttpClient())
{
httpClient.DefaultRequestHeaders.Add("mac", GlobalClientConfig.MacAddress); var requestMessage = JsonConvert.SerializeObject(data, new IsoDateTimeConverter());
HttpContent contentPost = new StringContent(requestMessage, Encoding.UTF8, "application/json");
var response = httpClient.PostAsync(endpoint, contentPost).Result;
if (response.StatusCode != HttpStatusCode.OK)
{
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
throw new UnauthorizedAccessException();
}
else
{
throw new Exception("Invoke Server Service Error");
}
} string result = response.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<TRetrun>(result);
}
}
#endregion #region PostByDictionay 字典处理POST
public static Dictionary<string, object> PostByDictionay<T>(T data, string endpoint)
{
using (var httpClient = NewHttpClient())
{
httpClient.DefaultRequestHeaders.Add("mac", GlobalClientConfig.MacAddress); var requestMessage = JsonHelper.JsonSerializer<T>(data);
HttpContent contentPost = new StringContent(requestMessage, Encoding.UTF8, "application/json");
var response = httpClient.PostAsync(endpoint, contentPost).Result;
if (response.StatusCode != HttpStatusCode.OK)
{
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
throw new UnauthorizedAccessException();
}
else
{
throw new Exception("Invoke Server Service Error");
}
} string result = response.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<Dictionary<string, object>>(result);
}
} /// <summary>
/// 注册设备MAC同步服务器,无需验证
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data"></param>
/// <param name="endpoint"></param>
/// <returns></returns>
public static string PostDevice<T>(T data, string endpoint)
{
using (var httpClient = NewHttpClient())
{
httpClient.DefaultRequestHeaders.Add("mac", GlobalClientConfig.MacAddress); var requestMessage = JsonHelper.JsonSerializer<T>(data);
HttpContent contentPost = new StringContent(requestMessage, Encoding.UTF8, "application/json");
var response = httpClient.PostAsync(endpoint, contentPost).Result;
string result = response.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<string>(result);
}
}
#endregion #region 其他i请求
public static string GetObjectPropertyValue<T>(T t)
{
StringBuilder sb = new StringBuilder();
Type type = typeof(T);
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
if (property != null && t != null)
{
object o = property.GetValue(t, null);
if (o != null)
{
sb.Append("&" + property.Name + "=" + o); ;
}
}
}
return sb.ToString();
} public static T GetOne<T>(string endpoint)
{
T obj;
using (var httpClient = NewHttpClient())
{
httpClient.DefaultRequestHeaders.Add("mac", GlobalClientConfig.MacAddress); var response = httpClient.GetAsync(endpoint).Result;
if (response.StatusCode != HttpStatusCode.OK)
{
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
throw new UnauthorizedAccessException();
}
else
{
throw new Exception("Invoke Server Service Error");
}
} string result = response.Content.ReadAsStringAsync().Result;
obj = JsonConvert.DeserializeObject<T>(result);
return obj;
}
} public static T CheckWhetherInternet<T>(string endpoint)
{
T obj;
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("mac", GlobalClientConfig.MacAddress); var response = httpClient.GetAsync(endpoint).Result;
if (response.StatusCode != HttpStatusCode.OK)
{
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
throw new UnauthorizedAccessException();
}
else
{
throw new Exception("Invoke Server Service Error");
}
} string result = response.Content.ReadAsStringAsync().Result;
obj = JsonConvert.DeserializeObject<T>(result);
return obj;
}
}
#endregion #region Delete 请求
public static string Delete<T>(T data, string endpoint)
{
using (var httpClient = NewHttpClient())
{
httpClient.DefaultRequestHeaders.Add("mac", GlobalClientConfig.MacAddress); var _endpoint = endpoint;
var requestMessage = GetObjectPropertyValue(data);
if (!string.IsNullOrEmpty(requestMessage))
{
_endpoint += "?" + requestMessage.Remove(, );
}
var result = httpClient.DeleteAsync(_endpoint).Result;
//return result.Content.ReadAsStringAsync().Result; string res = result.Content.ReadAsStringAsync().Result;
return res;
}
} public static string Delete(string id, string endpoint)
{
using (var httpClient = NewHttpClient())
{
var result = httpClient.DeleteAsync(endpoint + id).Result; return result.Content.ReadAsStringAsync().Result;
}
}
#endregion #region 初始化HttpClient
protected static HttpClient NewHttpClient()
{ var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
return new HttpClient(handler); }
#endregion #region 发起Json数据包请求
/// <summary>
/// 请求格式JSON数据格式
/// </summary>
/// <param name="posturl"></param>
/// <param name="postData"></param>
/// <returns></returns>
public static string GetUri(string posturl, string postData)
{ using (var http = new HttpClient())
{
var content = new StringContent(postData, Encoding.UTF8, "application/json");
//await异步等待回应
var response = http.PostAsync(posturl, content).Result; }
return null;
}
#endregion #region 这是HttpWebRequest请求方式
public static string GetPage(string posturl, string postData)
{
//WX_SendNews news = new WX_SendNews();
//posturl: news.Posturl;
//postData:news.PostData;
System.IO.Stream outstream = null;
Stream instream = null;
StreamReader sr = null;
HttpWebResponse response = null;
HttpWebRequest request = null;
Encoding encoding = Encoding.UTF8;
byte[] data = encoding.GetBytes(postData);
// 准备请求...
try
{
// 设置参数
request = WebRequest.Create(posturl) as HttpWebRequest;
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
outstream = request.GetRequestStream();
outstream.Write(data, , data.Length);
outstream.Close();
//发送请求并获取相应回应数据
response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
instream = response.GetResponseStream();
sr = new StreamReader(instream, encoding);
//返回结果网页(html)代码
string content = sr.ReadToEnd();
string err = string.Empty; return content;
}
catch (Exception ex)
{
string err = ex.Message;
return string.Empty;
}
}
#endregion
}
}
@陈卧龙的博客
HttpwebClient的四种请求方式的更多相关文章
- SpringMVC的REST风格的四种请求方式
一. 在HTTP 协议里面,四个表示操作方式的动词:GET.POST.PUT.DELETE. ·它们分别对应四种基本操作: 1.GET ====== 获 取资源 2.POST ======新建资源 ...
- 【spring springmvc】这里有你想要的SpringMVC的REST风格的四种请求方式
概述 之前的文章springmvc使用注解声明控制器与请求映射有简单提到过控制器与请求映射,这一次就详细讲解一下SpringMVC的REST风格的四种请求方式及其使用方法. 你能get的知识点 1.什 ...
- python写http post请求的四种请求体
Web自动化测试(25) HTTP 协议规定 POST 提交的数据必须放在消息主体(entity-body)中,但协议并没有规定数据必须使用什么编码方式.常见的四种编码方式如下: 1.appli ...
- Python请求外部POST请求,常见四种请求体
原文http://blog.csdn.net/silencemylove/article/details/50462206 HTTP 协议规定 POST 提交的数据必须放在消息主体(entity-bo ...
- 8237dma的四种传送方式简介
8237A有四种工作方式:单字节传送.数据块传送.请求传送和多片级联. (1)单字节传送(single mode) 单字节传送方式是每次DMA传送时,仅传送一个字节.传送一个字节之后,当前字节计数器减 ...
- 同步(Sync)/异步(Async),阻塞(Block)/非阻塞(Unblock)四种调用方式
1. 概念理解 在进行网络编程时,我们常常见到同步(Sync)/异步(Async),阻塞(Block)/非阻塞(Unblock)四种调用方式: 同步/异步主要针对C端: 同步: ...
- 接口测试中模拟post四种请求数据
https://www.jianshu.com/p/3b6d7aa2043a 一.背景介绍 在日常的接口测试工作中,模拟接口请求通常有两种方法,fiddler模拟和HttpClient模拟. Fidd ...
- spring security四种实现方式
spring security四种实现方式 spring(20) > 目录(?)[+] 最简单配置spring-securityxml实现1 实现UserDetailsService 实现动态过 ...
- Vue 封装axios(四种请求)及相关介绍(十三)
Vue 封装axios(四种请求)及相关介绍 首先axios是基于promise的http库 promise是什么? 1.主要用于异步计算 2.可以将异步操作队列化,按照期望的顺序执行,返回符合预期的 ...
随机推荐
- osgi 命令
安装命令 install reference:file:D:/workspace/workspace-osgi/MsgBoxCreateModule 根据 返回的 ID再运行start
- HTML5 本地存储 LocalStorage
说到本地存储,这玩意真是历尽千辛万苦才走到HTML5这一步,之前的历史大概如下图所示: 最早的Cookies自然是大家都知道,问题主要就是太小,大概也就4KB的样子,而且IE6只支持每个域名20个co ...
- ServletDemo
1. Servlet 接口 继承 Servlet 接口,实现Servlet 接口的 所有抽象方法! 实现类代码 package xw.servlet; import java.io.IOExcepti ...
- SVM神经网络的术语理解
SVM(Support Vector Machine)翻译成中文是支持向量机, 这里的“机(machine,机器)”实际上是一个算法.而支持向量则是指那些在间隔区边缘的训练样本点[1]. 当初看到这个 ...
- mysql参数,蛮全的
网上有很多的文章教怎么配置MySQL服务器,但考虑到服务器硬件配置的不同,具体应用的差别,那些文章的做法只能作为初步设置参考,我们需要根据自己的情况进行配置优化,好的做法是MySQL服务器稳定运行了一 ...
- NSURL基本操作示例说明
http://blog.csdn.net/zhibudefeng/article/details/7920686
- Flume协作框架
1.概述 ->flume的三大功能 collecting, aggregating, and moving 收集 聚合 移动 2.框图 3.架构特点 ->on streaming data ...
- Win7下VS2008编译QtiPlot
Win7下VS2008编译QtiPlot By wangsh 2011-11-25 QtiPlot 是一款开源免费的科学绘图软件,可运行在多个平台(windows.Linux等)中,从功能上讲,Qti ...
- ArcGIS中如何导出单个矢量要素图形
原文:ArcGIS中如何导出单个矢量要素图形 在ARCGIS中载入了一张含有省界的中国地图,是SHP文件.现在我只想要其中一块地区的,实现方法如下: 加入到ArcGIS后,右击图层,打开属性表(att ...
- There has been an error processing your request magento
如果使用magento的过程中,出现以下页面: 说明出现了错误,但是亲,不用紧张,请根据"Error record number:xxxxxxxxx"的数字在网站根目录下的var/ ...