WebClient请求帮助类
/// <summary>
/// 通过JSON方式发送POST请求
/// 将返回结果按JSON方式解析
/// </summary>
public static class WebClientHelper
{
const string REQUEST_HEADER_BEARER = "bearer"; /// <summary>
/// 通过POST方式调用WEB API
/// 期待返回值为JSON字符串,并自动转换为期望的对象类型
/// 如果想直接获得原始的返回字符串,则T传为string
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url"></param>
/// <param name="postData">post数据。自动转换为json格式,可以为空</param>
/// <param name="accessToken">调用FIDP API时,需要填写Access Token</param>
/// <returns></returns>
public static T Post<T>(string url, object postData, bool bNeedToken = true) where T : class
{
string accessToken = bNeedToken ? TokenCache.GetAccessToken() : null;
using (var wc = MyWebClient(accessToken))
{
string postJson = string.Empty;
if (postData != null) postJson = JsonConvert.SerializeObject(postData); string response = wc.UploadString(url, postJson);
if (typeof(T) == typeof(string)) return response as T;
T ret = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(response); return ret;
}
} /// <summary>
/// POST的异步版本
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <param name="accessToken"></param>
/// <returns></returns>
public static async Task<T> PostAsync<T>(string url, object postData, bool bNeedToken = true) where T : class
{
string accessToken = bNeedToken ? TokenCache.GetAccessToken() : null;
using (var wc = MyWebClient(accessToken))
{
string postJson = string.Empty;
if (postData != null) postJson = JsonConvert.SerializeObject(postData); string response = await wc.UploadStringTaskAsync(url, postJson);
if (typeof(T) == typeof(string)) return response as T; T ret = JsonConvert.DeserializeObject<T>(response); return ret; }
} /// <summary>
/// 通过GET方式调用WEB API
/// 期待返回值为JSON字符串,并自动转换为期望的对象类型
/// 如果想直接获得原始的返回字符串,则T传为string
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url"></param>
/// <param name="accessToken"></param>
/// <returns></returns>
public static T Get<T>(string url, bool bNeedToken = true) where T : class
{
string accessToken = bNeedToken ? TokenCache.GetAccessToken() : null;
using (var wc = MyWebClient(accessToken))
{
string response = wc.DownloadString(url); if (typeof(T) == typeof(string)) return response as T; T ret = JsonConvert.DeserializeObject<T>(response); return ret;
}
} public static string Get(string url, bool bNeedToken = true)
{
string accessToken = bNeedToken ? TokenCache.GetAccessToken() : null;
using (var wc = MyWebClient(accessToken))
{
string response = wc.DownloadString(url);
return response;
}
} /// <summary>
/// GET的异步版本
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url"></param>
/// <param name="accessToken"></param>
/// <returns></returns>
public static async Task<T> GetAsync<T>(string url, bool bNeedToken = true) where T : class
{
string accessToken = bNeedToken ? TokenCache.GetAccessToken() : null;
using (var wc = MyWebClient(accessToken))
{
string response = await wc.DownloadStringTaskAsync(url); if (typeof(T) == typeof(string)) return response as T; T ret = JsonConvert.DeserializeObject<T>(response); return ret;
}
} private static WebClient MyWebClient(string accessToken)
{
var wc = new WebClient { Encoding = Encoding.UTF8 }; wc.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8");
wc.Headers.Add(HttpRequestHeader.Accept, "*/*");
wc.Headers.Add(HttpRequestHeader.AcceptCharset, "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
if (!string.IsNullOrEmpty(accessToken)) wc.Headers.Add(HttpRequestHeader.Authorization, REQUEST_HEADER_BEARER + " " + accessToken); return wc;
} /// <summary>
/// 上传文件
/// </summary>
/// <param name="url"></param>
/// <param name="file"></param>
/// <param name="bNeedToken"></param>
/// <returns></returns>
public static string UploadFile(string url, string file, bool bNeedToken = false)
{
string accessToken = bNeedToken ? TokenCache.GetAccessToken() : null;
using (var wc = MyWebClient(accessToken))
{
var b = wc.UploadFile(url, file);
return Encoding.UTF8.GetString(b);
}
} }
public class TokenCache
{
static TokenInfo tokenInfo = new TokenInfo();
static JwtCore jwtCore = new JwtCore(); static ICacheManager<TokenInfo> accessTokenCache = CacheFactory.FromConfiguration<TokenInfo>("tokenCache"); /// <summary>
/// SSO Clock Skew(秒):时钟调整,适配不同服务器之间的时钟偏差
/// </summary>
static readonly int CLOCK_SKEW_IN_SECONDS = int.Parse(ConfigurationManager.AppSettings["SSO:CLOCK_SKEW_IN_SECONDS"]); /// <summary>
/// AppInfo
/// </summary>
static readonly string AppId = ConfigurationManager.AppSettings["AppId"];
static readonly string AppSecret = ConfigurationManager.AppSettings["AppSecret"];
static public string GetAccessToken()
{
lock(tokenInfo)
{
return getAccessToken();
}
} static string getAccessToken()
{
string tokenKey = AppId; var ti = accessTokenCache.Get(tokenKey);
if(ti != null)
{
return ti.Token;
} // request a new access-token
string urlAccessToken = ApiConfig.Instance.GetUrl("sso.access_token");
Debug.Assert(!string.IsNullOrEmpty(urlAccessToken));
SSOAccessTokenReq req = new SSOAccessTokenReq()
{
AppId = AppId,
AppSecret = AppSecret,
//StoreCode,UserCode
}; //try
{
var ret = WebClientHelper.Post<ApiResultT<string>>(urlAccessToken, req, false);
if (ret.IsSuccess())
{
JwtPayload jwtPayload; var ret2 = jwtCore.ValidateToken(ret.data, out jwtPayload);
if (ret2.IsSuccess())
{
tokenInfo.Token = ret.data;
tokenInfo.ExpireAt = jwtPayload.exp; accessTokenCache.Add(tokenKey, tokenInfo); return tokenInfo.Token;
}
throw new Exception("Access Token 无效:" + ret2.ToString());
} throw new Exception("获取Access Token失败:" + ret.ToString());
}
//catch(WebException ex)
//{
// HttpWebResponse httpRep = ex.Response as HttpWebResponse;
// if (httpRep != null)
// {
// if(httpRep.StatusCode == HttpStatusCode.Forbidden)
// { // } // }
//} } internal class TokenInfo
{
public string Token { get; set; } /// <summary>
/// 到期时间:Unix Timestamp
/// </summary>
public long ExpireAt { get; set; }
} }
WebClient请求帮助类的更多相关文章
- C# http请求工具类
/// <summary> /// Http请求操作类之HttpWebRequest /// </summary> public class HttpHelper { #reg ...
- WebUtils-网络请求工具类
网络请求工具类,大幅代码借鉴aplipay. using System; using System.Collections.Generic; using System.IO; using System ...
- Http、Https请求工具类
最近在做微信开发,使用http调用第三方服务API,有些是需要https协议,通过资料和自己编码,写了个支持http和https的工具类,经验证可用,现贴出来保留,也供需要的人使用(有不足的地方,也请 ...
- 微信https请求工具类
工作中用到的微信https请求工具类. package com.gxgrh.wechat.tools; import com.gxgrh.wechat.wechatapi.service.System ...
- HTTP请求工具类
HTTP请求工具类,适用于微信服务器请求,可以自测 代码; /// <summary> /// HTTP请求工具类 /// </summary> public class Ht ...
- Java请求参数类QueryParameter
import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; /** * 请求 ...
- 实现一个简单的http请求工具类
OC自带的http请求用起来不直观,asihttprequest库又太大了,依赖也多,下面实现一个简单的http请求工具类 四个文件源码大致如下,还有优化空间 MYHttpRequest.h(类定义, ...
- C# 中使用WebClient 请求 https
WebClient 请求 启用SSL的站点 时,如果站点的证书是不可信的,请求会被阻止,解决办法如下: 添加以下代码: ServicePointManager.ServerCertificateVal ...
- 远程Get,Post请求工具类
1.远程请求工具类 import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.L ...
随机推荐
- django 生成csv文件重要代码
import csv from django.http import HttpResponse # Number of unruly passengers each year 1995 - 2005. ...
- python模块之imghdr(识别不同格式的图片文件)
# -*- coding: utf-8 -*- #python 27 #xiaodeng #python模块之imghdr(识别不同格式的图片文件) import imghdr '''>> ...
- python之函数用法startswith()
# -*- coding: utf-8 -*- #python 27 #xiaodeng #python之函数用法startswith() #http://www.runoob.com/python/ ...
- shell笔记-算术运算
算术运算在Bash shell环境中,可以利用let.(( ))和[]执行基本的算术操作.而在进行高级操作时,expr和bc这两个工具也会非常有用.let命令可以直接执行基本的算术操作.当使用let时 ...
- 基于Echarts的中国地图数据展示
发布时间:2018-10-31 技术:javascript+html5+canvas 概述 基于echarts的大数据中国地图展示,结合API定制,开发样式,监听鼠标事件,实现带参数路由跳转等 ...
- 【PHP】Ajax跨域解决方案 、jsonp、cors
参考文章: 1.https://blog.csdn.net/u014727260/article/details/72793459 (后台java,实际上差不多) 2. 如何解决ajax跨域传输 数据 ...
- (原)torch模型转pytorch模型
转载请注明出处: http://www.cnblogs.com/darkknightzh/p/7839263.html 目前使用的torch模型转pytorch模型的程序为: https://gith ...
- spring 自动装配 default-autowire="byName/byType"
<PRE class=html name="code">spring 自动装配 default-autowire="byName/byType" ...
- Tensorflow get_variable和Varialbe的区别
import tensorflow as tf """ tf.get_variable()和Variable有很多不同点 * 它们对重名操作的处理不同 * 它们受name ...
- JavaScript 字符串(String)对象
String 对象 String 对象用于处理文本(字符串). 创建 String 对象的语法: new String(s); String(s); 参数 参数 s 是要存储在 String 对象中或 ...