using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Web; namespace AirMedia.Wap.Core
{
public static class HttpWebHelper
{
/// <SUMMARY>
/// httpwebrequest类中的一些属性的集合
/// </SUMMARY>
public class RequestParam
{
/// <SUMMARY>
/// 获取或设置request类中的Accept属性
/// 用以设置接受的文件类型
/// </SUMMARY>
public string Accept { get; set; } /// <SUMMARY>
/// 获取或设置request类中的ContentType属性
/// 用以设置请求的媒体类型
/// </SUMMARY>
public string ContentType { get; set; } /// <SUMMARY>
/// 获取或设置request类中的UserAgent属性
/// 用以设置请求的client信息
/// </SUMMARY>
public string UserAgent { get; set; } /// <SUMMARY>
/// 获取或设置request类中的Method属性
/// 能够将 Method 属性设置为不论什么 HTTP 1.1 协议谓词:GET、HEAD、POST、PUT、DELETE、TRACE 或 OPTIONS。 /// 假设 ContentLength 属性被设置为 -1 以外的不论什么值。则必须将 Method 属性设置为上载数据的协议属性。 /// </SUMMARY>
public string Method { get; set; } /// <summary>
/// 发送的数据
/// </summary>
public byte[] PostData { get; set; }
}
/// <SUMMARY>
/// 构建一个httt请求以获取目标链接的cookies,须要传入目标的登录地址和相关的post信息,返回完毕登录的cookies,以及返回的html内容
/// </SUMMARY>
/// <PARAM name="url">登录页面的地址</PARAM>
/// <PARAM name="post">post信息</PARAM>
/// <PARAM name="strHtml">输出的html代码</PARAM>
/// <PARAM name="rppt">请求的标头所须要的相关属性设置</PARAM>
/// <RETURNS>请求完毕后的cookies</RETURNS>
public static CookieCollection GetCookie(string url, RequestParam rppt, out string strHtml)
{ CookieCollection ckclReturn = new CookieCollection();
CookieContainer cc = new CookieContainer();
HttpWebRequest hwRequest;
HttpWebResponse hwResponse;
Stream stream; hwRequest = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
hwRequest.CookieContainer = cc;
if (rppt != null)
{
hwRequest.Accept = rppt.Accept;
hwRequest.ContentType = rppt.ContentType;
hwRequest.UserAgent = rppt.UserAgent;
hwRequest.Method = rppt.Method;
hwRequest.ContentLength = rppt.PostData.Length;
//写入标头 stream = hwRequest.GetRequestStream();
stream.Write(rppt.PostData, 0, rppt.PostData.Length);
stream.Close();
}
//发送请求获取响应内容
try
{
hwResponse = (HttpWebResponse)hwRequest.GetResponse();
}
catch
{
strHtml = "";
return ckclReturn;
}
stream = hwResponse.GetResponseStream();
StreamReader sReader = new StreamReader(stream, Encoding.UTF8);
strHtml = sReader.ReadToEnd();
sReader.Close();
stream.Close();
//获取缓存内容
ckclReturn = hwResponse.Cookies;
return ckclReturn;
} /// <SUMMARY>
/// 依据已经获取的有效cookies来获取目标链接的内容
/// </SUMMARY>
/// <PARAM name="strUri">目标链接的url</PARAM>
///<PARAM name="post">post的byte信息</PARAM>
/// <PARAM name="ccl">已经获取到的有效cookies</PARAM>
/// <PARAM name="rppt">头属性的相关设置</PARAM>
/// <RETURNS>目标连接的纯文本:"txt/html"</RETURNS>
public static string GetHtmlByCookies(string strUri, byte[] post, CookieCollection ccl, RequestParam rppt)
{
CookieContainer cc = new CookieContainer();
HttpWebRequest hwRequest;
HttpWebResponse hwResponse; //构建即将发送的包头
hwRequest = (HttpWebRequest)HttpWebRequest.Create(new Uri(strUri));
cc.Add(ccl);
hwRequest.CookieContainer = cc;
hwRequest.Accept = rppt.Accept;
hwRequest.ContentType = rppt.ContentType;
hwRequest.UserAgent = rppt.UserAgent;
hwRequest.Method = rppt.Method;
hwRequest.ContentLength = post.Length;
//写入post信息
Stream stream;
stream = hwRequest.GetRequestStream();
stream.Write(post, 0, post.Length);
stream.Close();
//发送请求获取响应内容
try
{
hwResponse = (HttpWebResponse)hwRequest.GetResponse();
}
catch
{
return "";
} stream = hwResponse.GetResponseStream();
StreamReader sReader = new StreamReader(stream, Encoding.Default);
string strHtml = sReader.ReadToEnd();
sReader.Close();
stream.Close(); //返回值
return strHtml;
} /// <summary>
/// 依据泛型来构建字符串用于post
/// </summary>
/// <param name="dir">带有键值对的泛型</param>
/// <returns>构建完毕的字符串</returns>
public static byte[] CreatePostData(Dictionary<string, string> dir)
{
StringBuilder strPost = new StringBuilder();
foreach (KeyValuePair<string, string> kvp in dir)
{
strPost.Append(kvp.Key);
strPost.Append('=');
if (!string.IsNullOrWhiteSpace(kvp.Value))
{
strPost.Append(System.Web.HttpUtility.UrlEncode(kvp.Value));
}
strPost.Append('&');
}
return CreatePostData(strPost.ToString().TrimEnd('&'));
} public static byte[] CreatePostData(string input)
{
return Encoding.Default.GetBytes(input);
} /// <summary>
/// 向指定uri发起GET请求
/// </summary>
/// <param name="uri"></param>
/// <param name="request"></param>
/// <returns></returns>
public static string GET(string url)
{
WebClient wc = new WebClient();
wc.Encoding = System.Text.Encoding.UTF8;
string s = wc.DownloadString(url);
s = HttpUtility.UrlDecode(s);
return s;
}
} /// <summary>
/// 有关HTTP请求的辅助类
/// </summary>
public class HttpWebResponseUtility
{
private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
/// <summary>
/// 创建GET方式的HTTP请求
/// </summary>
/// <param name="url">请求的URL</param>
/// <param name="timeout">请求的超时时间</param>
/// <param name="userAgent">请求的client浏览器信息。能够为空</param>
/// <param name="cookies">随同HTTP请求发送的Cookie信息,假设不须要身份验证能够为空</param>
/// <returns></returns>
public static HttpWebResponse CreateGetHttpResponse(string url, IDictionary<string, string> parameters, int? timeout, string userAgent, Encoding requestEncoding, CookieCollection cookies)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentNullException("url");
}
StringBuilder buffer = new StringBuilder();
if (!(parameters == null || parameters.Count == 0))
{ int i = 0;
foreach (string key in parameters.Keys)
{
if (i > 0)
{
buffer.AppendFormat("&{0}={1}", key, parameters[key]);
}
else
{
buffer.AppendFormat("{0}={1}", key, parameters[key]);
}
i++;
}
} if (buffer.Length > 1)
{
url = url + "? " + buffer.ToString();
}
url = HttpUtility.UrlDecode(url);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "GET";
request.UserAgent = DefaultUserAgent;
if (!string.IsNullOrEmpty(userAgent))
{
request.UserAgent = userAgent;
}
if (timeout.HasValue)
{
request.Timeout = timeout.Value;
}
if (cookies != null)
{
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
}
return request.GetResponse() as HttpWebResponse;
}
/// <summary>
/// 创建POST方式的HTTP请求
/// </summary>
/// <param name="url">请求的URL</param>
/// <param name="parameters">随同请求POST的參数名称及參数值字典</param>
/// <param name="timeout">请求的超时时间</param>
/// <param name="userAgent">请求的client浏览器信息。能够为空</param>
/// <param name="requestEncoding">发送HTTP请求时所用的编码</param>
/// <param name="cookies">随同HTTP请求发送的Cookie信息,假设不须要身份验证能够为空</param>
/// <returns></returns>
public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, int? timeout, string userAgent, Encoding requestEncoding, CookieCollection cookies)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentNullException("url");
}
if (requestEncoding == null)
{
throw new ArgumentNullException("requestEncoding");
}
HttpWebRequest request = null;
//假设是发送HTTPS请求
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
}
request.Method = "POST";
// request.ContentType = "application/x-www-form-urlencoded";
request.ContentType = "application/json";
if (!string.IsNullOrEmpty(userAgent))
{
request.UserAgent = userAgent;
}
else
{
request.UserAgent = DefaultUserAgent;
} if (timeout.HasValue)
{
request.Timeout = timeout.Value;
}
if (cookies != null)
{
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
}
//假设须要POST数据
if (!(parameters == null || parameters.Count == 0))
{
StringBuilder buffer = new StringBuilder();
int i = 0;
foreach (string key in parameters.Keys)
{
if (i > 0)
{
buffer.AppendFormat("&{0}={1}", key, parameters[key]);
}
else
{
buffer.AppendFormat("{0}={1}", key, parameters[key]);
}
i++;
}
byte[] data = requestEncoding.GetBytes(buffer.ToString());
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
}
return request.GetResponse() as HttpWebResponse;
} private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true; //总是接受
} public static string PostXml(string url, string xml)
{
byte[] bytes = Encoding.UTF8.GetBytes(xml);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentLength = bytes.Length;
request.ContentType = "text/xml";
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
} HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode != HttpStatusCode.OK)
{
string message = String.Format("POST failed. Received HTTP {0}",
response.StatusCode);
throw new ApplicationException(message);
}
System.IO.StreamReader sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"));
string res = sr.ReadToEnd();
sr.Close();
response.Close();
return res;
}
}
}

调用

string requestUrl = CoreInterface.ApiDomain + "api/Login/AddQRLog?

grid={0}&ad={1}&grName={2}&vc={3}&br={4}&sc={5}&ts={6}&ps={7}";
requestUrl = string.Format(requestUrl, grid, ad, grName, vc, br, sc, ts, ps);
string resultJson = "";
//try
//{
HttpWebResponse response = HttpWebResponseUtility.CreateGetHttpResponse(requestUrl, null, 1000000, "", null, null);
System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
resultJson = sr.ReadToEnd();
sr.Close();
//}
//catch (Exception)
//{
// return RedirectToAction("Index", "Error");
//}

C# 自带JSON转换类

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization.Json; namespace AirMedia.Wap.Core
{
public static class JsonHelper
{
#region DataContractJsonSerializer /// <summary>
/// 对象转换成json
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonObject">须要格式化的对象</param>
/// <returns>Json字符串</returns>
public static string DataContractJsonSerialize<T>(T jsonObject)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
string json = null;
using (MemoryStream ms = new MemoryStream()) //定义一个stream用来存发序列化之后的内容
{
serializer.WriteObject(ms, jsonObject);
json = Encoding.UTF8.GetString(ms.GetBuffer()); //将stream读取成一个字符串形式的数据。而且返回
ms.Close();
}
return json;
} /// <summary>
/// json字符串转换成对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="json">要转换成对象的json字符串</param>
/// <returns></returns>
public static T DataContractJsonDeserialize<T>(string json)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
T obj = default(T);
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
obj = (T)serializer.ReadObject(ms);
ms.Close();
}
return obj;
} #endregion
}
}

/// <summary>

        /// 时间戳

        /// </summary>

        public static string TS

        {

            get

            {

                DateTime dt = new DateTime(1970, 1, 1);

                TimeSpan d = DateTime.Now - dt;

                long seconddiff = d.Ticks / 10000000;

                return seconddiff.ToString();

            }

        }

/// <summary>

        /// md5加密

        /// </summary>

        /// <param name="strText"></param>

        /// <returns></returns>

        public static string MD5Encrypt(string strText)

        {

            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strText, "MD5");

        }

C# 调用API接口处理公共类 自带JSON实体互转类的更多相关文章

  1. C#使用windows服务定时调用api接口

    使用VS创建windows服务项目: 创建好项目  会出现一个设计界面 右键弹出对话框 选择添加安装程序 名字什么的自己可以改: 项目目录: 打开项目中的ProjectInstaller.Design ...

  2. Python调用API接口的几种方式 数据库 脚本

    Python调用API接口的几种方式 2018-01-08 gaoeb97nd... 转自 one_day_day... 修改 微信分享: 相信做过自动化运维的同学都用过API接口来完成某些动作.AP ...

  3. Python调用API接口的几种方式

    Python调用API接口的几种方式 相信做过自动化运维的同学都用过API接口来完成某些动作.API是一套成熟系统所必需的接口,可以被其他系统或脚本来调用,这也是自动化运维的必修课. 本文主要介绍py ...

  4. 调用API接口,查询手机号码归属地(3)

    从mysql数据库获取电话号码,查询归属地并插入到数据库 #!/usr/bin/python # -*- coding: utf-8 -*- import json, urllib, sys, pym ...

  5. 调用API接口,查询手机号码归属地(2)

    使用pymysql pip install pymysql 创建mysql测试表 CREATE TABLE `userinfo` ( `id` int(20) NOT NULL AUTO_INCREM ...

  6. 调用API接口,查询手机号码归属地(1)

    使用https://www.juhe.cn/提供的接口,查询归属地 在官网注册key即可使用. 代码如下 #!/usr/bin/python # -*- coding: utf-8 -*- impor ...

  7. Apsara Clouder专项技能认证:实现调用API接口

    一.API 简介 1.API 的概念 API(Application Programming Interface应用程序编程接口)是一些预定义的函数,目的是提供应用程序与开发人员基于某软件或硬件得以访 ...

  8. spring boot 通过feign调用api接口

    目的:远程调用服务器api,直接上步骤: 1,添加maven依赖,这是必须的: <dependency> <groupId>org.springframework.cloud& ...

  9. 怎么调用api接口

    api的简单调用,调用api的方法 方法一:用前端方法调用api 完整代码: <!DOCTYPE html> <html lang="en"> <he ...

随机推荐

  1. [luogu1357] 花园 [dp+矩阵快速幂]

    题面: 传送门 思路: 把P形花圃记录为0,C形记录为1,那么一段花圃就可以状态压缩成一个整数 那么,我们可以有这样的状压dp: dp[i][S]表示前i个花圃,最后m个的状态为S的情况 如果这是一条 ...

  2. One-Way Streets (oneway)

    One-Way Streets (oneway) 题目描述 Once upon a time there was a country with nn cities and mm bidirection ...

  3. 安装淘宝内核LVS

    具体安装方法按照淘宝twiki来:http://kernel.taobao.org/index.php?title=Documents/Kernel_build. 但是有些问题是要注意的: 1. 修改 ...

  4. html5 的 webScoket 和 C# 建立Socket连接

    最近使用的web项目中,需要服务器直接触发前端显示效果. 所以研究了一下websocket: 名词解释: WebSocketWebSocket协议是一种双向通信协议,它建立在TCP之上,同http一样 ...

  5. 搭建git linux 服务器

    假设你已经有sudo权限的用户账号,下面,正式开始安装. 第一步,安装git: for Ubuntu或Debian $ sudo apt-get install git for Centos 更新一下 ...

  6. HDU 4388 Stone Game II {博弈||找规律}

    Stone Game II Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Tot ...

  7. c#.net前台调用JS文件中的函数[.net与JavaScript的应用]

    原文发布时间为:2008-10-10 -- 来源于本人的百度文章 [由搬家工具导入] <%@ Page Language="C#" AutoEventWireup=" ...

  8. CSS 黑魔法小技巧,让你少写不必要的JS,代码更优雅

    首页   登录注册         CSS 黑魔法小技巧,让你少写不必要的JS,代码更优雅 阅读 8113 收藏 927 2017-09-26 原文链接:github.com 腾讯云容器服务CSS,立 ...

  9. 《手把手教你学C语言》学习笔记(1)---C语言的特点

    学习C语言的原因,主要是需要使用C语言编程,我用故我学,应该是最主要的原因了. C语言的定位:C语言严格意义上只能算是中级语言,是面向过程编程语言的集大成者,虽然这种语言有很多的问题,但总体而言是瑕不 ...

  10. 修改手機的 input source 及 charger 及 usb 相關電路後,容易忽略的事項

    input source 及 charger 需要注意, 是否可以在關機的狀況下充電, 當然 開機充電 是一定要的. usb 部分需要注意, 是否可以在沒有電或者是有電的狀況下 download 程式 ...