引用 Newtonsoft.Json

        // Post请求
public string PostResponse(string url,string postData,out string statusCode)
{
string result = string.Empty;
//设置Http的正文
HttpContent httpContent = new StringContent(postData);
//设置Http的内容标头
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
//设置Http的内容标头的字符
httpContent.Headers.ContentType.CharSet = "utf-8";
using(HttpClient httpClient=new HttpClient())
{
//异步Post
HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
//输出Http响应状态码
statusCode = response.StatusCode.ToString();
//确保Http响应成功
if (response.IsSuccessStatusCode)
{
//异步读取json
result = response.Content.ReadAsStringAsync().Result;
}
}
return result;
} // 泛型:Post请求
public T PostResponse<T>(string url,string postData) where T:class,new()
{
T result = default(T); HttpContent httpContent = new StringContent(postData);
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
httpContent.Headers.ContentType.CharSet = "utf-8";
using(HttpClient httpClient=new HttpClient())
{
HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result; if (response.IsSuccessStatusCode)
{
Task<string> t = response.Content.ReadAsStringAsync();
string s = t.Result;
//Newtonsoft.Json
string json = JsonConvert.DeserializeObject(s).ToString();
result = JsonConvert.DeserializeObject<T>(json);
}
}
return result;
} // 泛型:Get请求
public T GetResponse<T>(string url) where T :class,new()
{
T result = default(T); using (HttpClient httpClient=new HttpClient())
{
httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = httpClient.GetAsync(url).Result; if (response.IsSuccessStatusCode)
{
Task<string> t = response.Content.ReadAsStringAsync();
string s = t.Result;
string json = JsonConvert.DeserializeObject(s).ToString();
result = JsonConvert.DeserializeObject<T>(json);
}
}
return result;
} // Get请求
public string GetResponse(string url, out string statusCode)
{
string result = string.Empty; using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = httpClient.GetAsync(url).Result;
statusCode = response.StatusCode.ToString(); if (response.IsSuccessStatusCode)
{
result = response.Content.ReadAsStringAsync().Result;
}
}
return result;
} // Put请求
public string PutResponse(string url, string putData, out string statusCode)
{
string result = string.Empty;
HttpContent httpContent = new StringContent(putData);
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
httpContent.Headers.ContentType.CharSet = "utf-8";
using (HttpClient httpClient = new HttpClient())
{
HttpResponseMessage response = httpClient.PutAsync(url, httpContent).Result;
statusCode = response.StatusCode.ToString();
if (response.IsSuccessStatusCode)
{
result = response.Content.ReadAsStringAsync().Result;
}
}
return result;
} // 泛型:Put请求
public T PutResponse<T>(string url, string putData) where T : class, new()
{
T result = default(T);
HttpContent httpContent = new StringContent(putData);
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
httpContent.Headers.ContentType.CharSet = "utf-8";
using(HttpClient httpClient=new HttpClient())
{
HttpResponseMessage response = httpClient.PutAsync(url, httpContent).Result; if (response.IsSuccessStatusCode)
{
Task<string> t = response.Content.ReadAsStringAsync();
string s = t.Result;
string json = JsonConvert.DeserializeObject(s).ToString();
result = JsonConvert.DeserializeObject<T>(json);
}
}
return result;
}

出处:https://blog.csdn.net/sun_zeliang/article/details/81587835

========================================================

我自己把上面的修改下,可以不引用 Newtonsoft.Json  ,在POST模式的方法PostWebAPI增加了GZip的支持,请求超时设置,其他的功能可以自己去扩展,增加了简单调用的方式。

后续可以扩展异步方式、HttpWebRequest方式调用Webapi(待完成。。。)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization; namespace Car.AutoUpdate.Comm
{
public class WebapiHelper
{ #region HttpClient /// <summary>
/// Get请求指定的URL地址
/// </summary>
/// <param name="url">URL地址</param>
/// <returns></returns>
public static string GetWebAPI(string url)
{
string result = "";
string strOut = "";
try
{
result = GetWebAPI(url, out strOut);
}
catch (Exception ex)
{
LogHelper.Error("调用后台服务出现异常!", ex);
}
return result;
} /// <summary>
/// Get请求指定的URL地址
/// </summary>
/// <param name="url">URL地址</param>
/// <param name="statusCode">Response返回的状态</param>
/// <returns></returns>
public static string GetWebAPI(string url, out string statusCode)
{
string result = string.Empty;
statusCode = string.Empty;
try
{
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = httpClient.GetAsync(url).Result;
statusCode = response.StatusCode.ToString(); if (response.IsSuccessStatusCode)
{
result = response.Content.ReadAsStringAsync().Result;
}
else
{
LogHelper.Warn("调用后台服务返回失败:" + url + Environment.NewLine + SerializeObject(response));
}
}
}
catch (Exception ex)
{
LogHelper.Error("调用后台服务出现异常!", ex);
}
return result;
} /// <summary>
/// Get请求指定的URL地址
/// </summary>
/// <typeparam name="T">返回的json转换成指定实体对象</typeparam>
/// <param name="url">URL地址</param>
/// <returns></returns>
public static T GetWebAPI<T>(string url) where T : class, new()
{
T result = default(T);
try
{
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = httpClient.GetAsync(url).Result; if (response.IsSuccessStatusCode)
{
Task<string> t = response.Content.ReadAsStringAsync();
string s = t.Result;
string jsonNamespace = DeserializeObject<T>(s).ToString();
result = DeserializeObject<T>(s);
}
else
{
LogHelper.Warn("调用后台服务返回失败:" + url + Environment.NewLine + SerializeObject(response));
}
}
}
catch (Exception ex)
{
LogHelper.Error("调用后台服务出现异常!", ex);
} return result;
} /// <summary>
/// Post请求指定的URL地址
/// </summary>
/// <param name="url">URL地址</param>
/// <param name="postData">提交到Web的Json格式的数据:如:{"ErrCode":"FileErr"}</param>
/// <returns></returns>
public static string PostWebAPI(string url, string postData)
{
string result = "";
HttpStatusCode strOut = HttpStatusCode.BadRequest;
try
{
result = PostWebAPI(url, postData, out strOut);
}
catch (Exception ex)
{
LogHelper.Error("调用后台服务出现异常!", ex);
}
return result; } /// <summary>
/// Post请求指定的URL地址
/// </summary>
/// <param name="url">URL地址</param>
/// <param name="postData">提交到Web的Json格式的数据:如:{"ErrCode":"FileErr"}</param>
/// <param name="statusCode">Response返回的状态</param>
/// <returns></returns>
public static string PostWebAPI(string url, string postData, out HttpStatusCode httpStatusCode)
{
string result = string.Empty;
httpStatusCode = HttpStatusCode.BadRequest;
//设置Http的正文
HttpContent httpContent = new StringContent(postData);
//设置Http的内容标头
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
//设置Http的内容标头的字符
httpContent.Headers.ContentType.CharSet = "utf-8"; HttpClientHandler httpHandler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
try
{
//using (HttpClient httpClient = new HttpClient(httpHandler))
using (HttpClient httpClient = new HttpClient())
{
httpClient.Timeout = new TimeSpan(, , );
//异步Post
HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
//输出Http响应状态码
httpStatusCode = response.StatusCode;
//确保Http响应成功
if (response.IsSuccessStatusCode)
{
//异步读取json
result = response.Content.ReadAsStringAsync().Result;
}
else
{
LogHelper.Warn("调用后台服务返回失败:" + url + Environment.NewLine + SerializeObject(response));
}
}
}
catch (Exception ex)
{
LogHelper.Error("调用后台服务出现异常!", ex);
}
return result;
} /// <summary>
/// Post请求指定的URL地址
/// </summary>
/// <typeparam name="T">返回的json转换成指定实体对象</typeparam>
/// <param name="url">URL地址</param>
/// <param name="postData">提交到Web的Json格式的数据:如:{"ErrCode":"FileErr"}</param>
/// <returns></returns>
public static T PostWebAPI<T>(string url, string postData) where T : class, new()
{
T result = default(T); HttpContent httpContent = new StringContent(postData);
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
httpContent.Headers.ContentType.CharSet = "utf-8"; HttpClientHandler httpHandler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
try
{
using (HttpClient httpClient = new HttpClient(httpHandler))
{
HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result; if (response.IsSuccessStatusCode)
{
Task<string> t = response.Content.ReadAsStringAsync();
string s = t.Result;
//Newtonsoft.Json
string jsonNamespace = DeserializeObject<T>(s).ToString();
result = DeserializeObject<T>(s);
}
else
{
LogHelper.Warn("调用后台服务返回失败:" + url + Environment.NewLine + SerializeObject(response));
}
}
}
catch (Exception ex)
{
LogHelper.Error("调用后台服务出现异常!", ex);
}
return result;
} /// <summary>
/// Put请求指定的URL地址
/// </summary>
/// <param name="url">URL地址</param>
/// <param name="putData">提交到Web的Json格式的数据:如:{"ErrCode":"FileErr"}</param>
/// <returns></returns>
public static string PutWebAPI(string url, string putData)
{
string result = "";
string strOut = "";
result = PutWebAPI(url, putData, out strOut);
return result;
} /// <summary>
/// Put请求指定的URL地址
/// </summary>
/// <param name="url">URL地址</param>
/// <param name="putData">提交到Web的Json格式的数据:如:{"ErrCode":"FileErr"}</param>
/// <param name="statusCode">Response返回的状态</param>
/// <returns></returns>
public static string PutWebAPI(string url, string putData, out string statusCode)
{
string result = statusCode = string.Empty;
HttpContent httpContent = new StringContent(putData);
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
httpContent.Headers.ContentType.CharSet = "utf-8";
try
{
using (HttpClient httpClient = new HttpClient())
{
HttpResponseMessage response = httpClient.PutAsync(url, httpContent).Result;
statusCode = response.StatusCode.ToString();
if (response.IsSuccessStatusCode)
{
result = response.Content.ReadAsStringAsync().Result;
}
else
{
LogHelper.Warn("调用后台服务返回失败:" + url + Environment.NewLine + SerializeObject(response));
}
}
}
catch (Exception ex)
{
LogHelper.Error("调用后台服务出现异常!", ex);
}
return result;
} /// <summary>
/// Put请求指定的URL地址
/// </summary>
/// <typeparam name="T">返回的json转换成指定实体对象</typeparam>
/// <param name="url">URL地址</param>
/// <param name="putData">提交到Web的Json格式的数据:如:{"ErrCode":"FileErr"}</param>
/// <returns></returns>
public static T PutWebAPI<T>(string url, string putData) where T : class, new()
{
T result = default(T);
HttpContent httpContent = new StringContent(putData);
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
httpContent.Headers.ContentType.CharSet = "utf-8";
try
{
using (HttpClient httpClient = new HttpClient())
{
HttpResponseMessage response = httpClient.PutAsync(url, httpContent).Result; if (response.IsSuccessStatusCode)
{
Task<string> t = response.Content.ReadAsStringAsync();
string s = t.Result;
string jsonNamespace = DeserializeObject<T>(s).ToString();
result = DeserializeObject<T>(s);
}
else
{
LogHelper.Warn("调用后台服务返回失败:" + url + Environment.NewLine + SerializeObject(response));
}
}
}
catch (Exception ex)
{
LogHelper.Error("调用后台服务出现异常!", ex);
}
return result;
} /// <summary>
/// 对象转JSON
/// </summary>
/// <param name="obj">对象</param>
/// <returns>JSON格式的字符串</returns>
public static string SerializeObject(object obj)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
try
{
return jss.Serialize(obj);
}
catch (Exception ex)
{
LogHelper.Error("JSONHelper.SerializeObject 转换对象失败。", ex);
throw new Exception("JSONHelper.SerializeObject(object obj): " + ex.Message);
}
} /// <summary>
/// 将Json字符串转换为对像
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="json"></param>
/// <returns></returns>
public static T DeserializeObject<T>(string json)
{
JavaScriptSerializer Serializer = new JavaScriptSerializer();
T objs = default(T);
try
{
objs = Serializer.Deserialize<T>(json);
}
catch (Exception ex)
{
LogHelper.Error("JSONHelper.DeserializeObject 转换对象失败。", ex);
throw new Exception("JSONHelper.DeserializeObject<T>(string json): " + ex.Message);
}
return objs; } #endregion private static HttpResponseMessage HttpPost(string url, HttpContent httpContent)
{
HttpResponseMessage response = null;
HttpClientHandler httpHandler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
try
{
//using (HttpClient httpClient = new HttpClient(httpHandler))
using (HttpClient httpClient = new HttpClient())
{
httpClient.Timeout = new TimeSpan(, , );
//异步Post
response = httpClient.PostAsync(url, httpContent).Result;
}
}
catch (Exception ex)
{
LogHelper.Error("调用后台服务出现异常!", ex);
}
return response;
} }
}

下面再分享一个帮助类,有用到的做个参考吧

using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks; namespace WebCollect.CommonHelp
{
public static class CommonHelper
{
#region HttpClient
private static HttpClient _httpClient;
public static HttpClient httpClient
{
get
{
if (_httpClient == null)
{
_httpClient = new HttpClient();
_httpClient.Timeout = new TimeSpan(, , ); }
return _httpClient;
}
set { _httpClient = value; }
} #endregion #region get请求
/// <summary>
/// get请求返回的字符串
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static string GetRequestStr(string url)
{
try
{
var response = httpClient.GetAsync(new Uri(url)).Result;
return response.Content.ReadAsStringAsync().Result;
}
catch (Exception)
{
return null;
}
}
/// <summary>
/// get请求返回的二进制
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static byte[] GetRequestByteArr(string url)
{
try
{
var response = httpClient.GetAsync(new Uri(url)).Result;
return response.Content.ReadAsByteArrayAsync().Result;
}
catch (Exception)
{
return null;
}
}
#endregion #region post请求
/// <summary>
/// post请求返回的字符串
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static string PostRequestStr(string url)
{
try
{
string contentStr = "";
StringContent sc = new StringContent(contentStr);
sc.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");//todo
var response = httpClient.PostAsync(new Uri(url), sc).Result;
return response.Content.ReadAsStringAsync().Result;
}
catch (Exception)
{
return null;
}
}
#endregion }
}

C# HttpClient请求Webapi帮助类的更多相关文章

  1. HttpClient 请求WebApi

    HttpClient client = new HttpClient(); client.BaseAddress = new Uri(ConfigurationManager.AppSettings[ ...

  2. HttpClient后台post 请求webapi

    1.请求方法 /// <summary> /// httpClient 请求接口 /// </summary> /// <param name="url&quo ...

  3. C# HttpClient 请求认证、数据传输笔记

    目录 一,授权认证 二,请求类型 三,数据传输 C# HttpClient 请求认证.数据传输笔记 一,授权认证 客户端请求服务器时,需要通过授权认证许可,方能获取服务器资源,目前比较常见的认证方式有 ...

  4. 请求WebApi的几种方式

    目前所了解的请求WebAPI的方式有通过后台访问api 和通过js 直接访问api接口 首先介绍下通过后台访问api的方法,可以使用HttpClient的方式也可以使用WebRequest的方式 1. ...

  5. HttpClient请求服务器代码优化版

    HttpClient请求服务器代码优化版 首先,我在前面的两篇博文中介绍了在 Android中,除了使用java.net包下HttpUrlConnection的API访问HTTP服务之外,我们还可以换 ...

  6. Android使用HttpClient请求服务器代码优化版

    首先,我在前面的两篇博文中介绍了在Android中,除了使用java.net包下HttpUrlConnection的API访问HTTP服务之外,我们还可以换一种途径去完成工作.Android SDK附 ...

  7. httpclient与webapi

    System.Net.Http 是微软推出的最新的 HTTP 应用程序的编程接口, 微软称之为“现代化的 HTTP 编程接口”, 主要提供如下内容: 1. 用户通过 HTTP 使用现代化的 Web S ...

  8. HTTP请求客户端工具类

    1.maven 引入依赖 <dependency> <groupId>commons-httpclient</groupId> <artifactId> ...

  9. 发送http请求和https请求的工具类

    package com.haiyisoft.cAssistant.utils; import java.io.IOException;import java.util.ArrayList; impor ...

随机推荐

  1. 4.4 C++虚析构函数

    参考:http://www.weixueyuan.net/view/6373.html 总结: 构造函数是不能声明为虚函数的,析构函数可以被声明为虚函数. 将基类的析构函数声明为虚函数之后,派生类的析 ...

  2. window.setTimeout和window.setInterval的区别,及用其中一个方法记录时间。

    window.setTimeout(语句,时间)是在多久之后执行语句,语句只执行一次. window.setInterval(语句,时间)是每隔多久执行一次语句,语句循环执行. <!DOCTYP ...

  3. Linux文件系统命令 mkdir/rmdir

    命令名:mkdir 功能:创建一个文件夹,和touch的区别是,touch是创建一个文件,后面可以跟绝对路径和相对路径 eg: mkdir ren 命令名:rmdir 功能:删除一个文件夹

  4. java语言登陆界面(菜鸟版)

    最近在看的Java入门书是<Head First Java>,一本很棒的Java书. 老师要求的程序流程图我没有,之前我们的做法是写完代码再画流程图,我想这样的做法是不对的,流程图应该是在 ...

  5. Vuejs2.0学习(Render函数,createElement,vm.$slots)

    直接来到进阶部分, Render函数 直接来到Render,本来也想跳过,发现后面的路由貌似跟它还有点关联.先来看看Render 1.1 官网一开始就看的挺懵的,不知道讲的是啥,动手试了一下,一开头讲 ...

  6. MySQL:数据表基本操作

    数据表基本操作 注意点: 1.数据表中已经有数据时,轻易修改数据类型,有可能因为不同的数据类型的数据在机器 中存储的方式及长度并不相同,修改数据类型可能会影响到数据表中已有的数据类型. 2.  数据表 ...

  7. xampp 忘记密码的处理方式.

    网上看到一些方法: 大部分是第一种:  方法一 这个方法, 我使用的时候没有生效. -------------- 后来看到另外一种方法 .  直接替换user表的三个文件.  这个方法成功了. xam ...

  8. python 创建flask项目方法

    Flask是一个基于Python的web框架,它的设计目的是提供Web开发所需的最小功能子集. Flask与别的框架(尤其是采用其他编程语言的框架)的不同之处在于:它没有绑定诸如数据库查询或者表单处理 ...

  9. robotframework·WEB项目

    date:2018527 day11 一.项目分层 1.测试数据(配置变量,如网址.用户名.密码等) 2.关键字(关键字封装,要调用直接使用关键字名即可,输入内容.点击元素.滚动滑动条等等) 3.测试 ...

  10. ES6 箭头函数--特性

    如果箭头表达式仅仅就是简化了函数的命名,我们为什么要改变原来的习惯而去使用它呢?所以我们需要了解一下箭头函数的特性. 箭头函数内部没有constructor方法,也没有prototype,所以不支持n ...