最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来。

十年河东十年河西,莫欺少年穷。 

    本文旨在发布代码,供自己参考,也供大家参考,谢谢。

正题:

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的四种请求方式的更多相关文章

  1. SpringMVC的REST风格的四种请求方式

    一. 在HTTP 协议里面,四个表示操作方式的动词:GET.POST.PUT.DELETE. ·它们分别对应四种基本操作: 1.GET  ====== 获 取资源 2.POST ======新建资源 ...

  2. 【spring springmvc】这里有你想要的SpringMVC的REST风格的四种请求方式

    概述 之前的文章springmvc使用注解声明控制器与请求映射有简单提到过控制器与请求映射,这一次就详细讲解一下SpringMVC的REST风格的四种请求方式及其使用方法. 你能get的知识点 1.什 ...

  3. python写http post请求的四种请求体

      Web自动化测试(25)  HTTP 协议规定 POST 提交的数据必须放在消息主体(entity-body)中,但协议并没有规定数据必须使用什么编码方式.常见的四种编码方式如下: 1.appli ...

  4. Python请求外部POST请求,常见四种请求体

    原文http://blog.csdn.net/silencemylove/article/details/50462206 HTTP 协议规定 POST 提交的数据必须放在消息主体(entity-bo ...

  5. 8237dma的四种传送方式简介

    8237A有四种工作方式:单字节传送.数据块传送.请求传送和多片级联. (1)单字节传送(single mode) 单字节传送方式是每次DMA传送时,仅传送一个字节.传送一个字节之后,当前字节计数器减 ...

  6. 同步(Sync)/异步(Async),阻塞(Block)/非阻塞(Unblock)四种调用方式

    1. 概念理解        在进行网络编程时,我们常常见到同步(Sync)/异步(Async),阻塞(Block)/非阻塞(Unblock)四种调用方式:   同步/异步主要针对C端: 同步:    ...

  7. 接口测试中模拟post四种请求数据

    https://www.jianshu.com/p/3b6d7aa2043a 一.背景介绍 在日常的接口测试工作中,模拟接口请求通常有两种方法,fiddler模拟和HttpClient模拟. Fidd ...

  8. spring security四种实现方式

    spring security四种实现方式 spring(20) > 目录(?)[+] 最简单配置spring-securityxml实现1 实现UserDetailsService 实现动态过 ...

  9. Vue 封装axios(四种请求)及相关介绍(十三)

    Vue 封装axios(四种请求)及相关介绍 首先axios是基于promise的http库 promise是什么? 1.主要用于异步计算 2.可以将异步操作队列化,按照期望的顺序执行,返回符合预期的 ...

随机推荐

  1. Memcached 笔记与总结(4)memcache 扩展的使用

    在 wamp 环境下进行测试:WAMPSERVER 2.2(Windows 7 + Apache 2.2.21 + PHP 5.3.10 + memcache 3.0.8 + Memcached 1. ...

  2. 放到u-boot/arch/arm/inlcude下面解压A20固件库制作笔记

    运行 build_dragonboard.sh,完成一次编译,首次编译需要消耗 20 分钟以上的时间.这里包括编译bootloader.kernel.rootfs. 修改 Linux 内核配置$ cd ...

  3. 【转载】C编译过程概述

    gcc:http://www.cnblogs.com/ggjucheng/archive/2011/12/14/2287738.html#_Toc311642844 gdb:http://www.cn ...

  4. Scrapy安装介绍

    一. Scrapy简介 Scrapy is a fast high-level screen scraping and web crawling framework, used to crawl we ...

  5. 学习之道-从求和起-求和曲线面积瞬时速率极限微积分---求和由高解低已知到未知高阶到低阶连续自然数的K次方之和

    数学分析 张筑生

  6. Greedy_algorithm

    https://en.wikipedia.org/wiki/Greedy_algorithm

  7. 分页查询:使用分页类查询 用get传值

    <body> <?php $cx = ""; if(!empty($_GET["cx"])) //判断get传过来的值非空,那么把传过来的值赋 ...

  8. c语言学习上的思考与心得

    由于这段时间在c语言的学习中,表现的很努力并且完成作业态度认真,所以得到了老师奖励的小黄衫. 以下是我对于c语言的学习感受与心得. 学习感受与心得 我选择计算机的这个专业,是因为我对计算机的学习很有兴 ...

  9. Redis学习笔记(9)-管道/分布式

    package cn.com; import java.util.Arrays; import java.util.List; import redis.clients.jedis.Jedis; im ...

  10. [LeetCode]题解(python):078 Subsets

    题目来源 https://leetcode.com/problems/subsets/ Given a set of distinct integers, nums, return all possi ...