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.可以将异步操作队列化,按照期望的顺序执行,返回符合预期的 ...
随机推荐
- NV SDK 9.5, 10 and 11
NVIDIA SDK 10 Overview This all-new collection of DirectX 10 and OpenGL code samples teaches devel ...
- ThinkPHP的cookide保存二维数组的方法
ThinkPHP中的cookie是不支持二维数组的. 如果要保存二维数组.只能特殊处理 $data[263] = array('gid'=>263,'num'=>1); $data[266 ...
- 【IOS笔记】Gesture Recognizers
Gesture Recognizers Gesture recognizers convert low-level event handling code into higher-level acti ...
- JS中基本window对象操作
---恢复内容开始--- 一.使用window中的属性时 window.属性,直接跟属性名.而调用window的函数时 window.hanshu(): 要在其函数名后面加括号. 二.windo ...
- 初次接触Groovy
其实我这两年业余时间一直断断续续的在学java,水平还不怎么样,不过起码能参与小项目写写接口了.现在我决定暂时放下大众的java,改学小众的Groovy,只因为我新拿到个offer,对方公司的自动化框 ...
- C#窗体:关于DataGridView的数据源绑定字符串两个值得注意的问题
无意间遇到的问题,然后就GOOGLE了下,搜到些资料,总结整理如下(注:是转载的) 1. LINQ的查询结果无法直接作为DataGridView的数据源 DataGridView的DataSource ...
- IOS 跳转时传参数的常用方法
在iOS开发中常用的参数传递有以下几种方法: 采用代理模式 采用iOS消息机制 通过NSDefault存储(或者文件.数据库存储等) 通过AppDelegate定义全局变量(或者使用UIApplica ...
- sublimtext2 资源
https://github.com/qljiong/soda-theme/blob/master/README.md http://my.oschina.net/ruochenchen/blog/9 ...
- WCF TCP 错误代码 10061: 由于目标计算机积极拒绝
表象是连不上服务端,本质原因多种多样,网络硬件问题导致的网络不通.服务本身问题或没有启动.或者防火墙阻隔等等不一而足. 1.ping看服务端能否ping通: 2.telnet ip地址 端口 ,看看是 ...
- LTRIM(str):返回 字符串str的前导(左边)空格字符去掉。
SELECT ' 11' res SELECT LTRIM(' 11') resL 运行结果: