引言
在日常开发中经常会对接第三方接口,所以经常需要封装第三方接口,方便在程序中使用,本文主要是封装JSON格式的HTTP第三方接口,将入参和出参都从json对象转化为class ,方便调用。
实现思路,应用
反射typeof()、
HttpWebRequest、
泛型类、
Newtonsoft.Json,
将一个http请求的过程封装聚合起来。
具体代码如下:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Newtonsoft.Json;
namespace Sample.Api
{
public class SampleApi
{
#region data
//通过配置文件获取第三方接口的url共同头部
public static string ApiUrl = ConfigurationManager.AppSettings["ApiUrl"];//如:http://localhost:8080/
#endregion
#region Base 基本封装实现
public class HttpResponse
{
public HttpStatusCode Statue {
get; set; }
public string Data {
get; set; }
}
/// <summary>
/// http请求类型
/// </summary>
public enum RequestMethod
{
Post = 0,
Get = 1,
Put = 2,
Delete = 3
}
public class HttpResponseResult<TRetData>
{
public HttpStatusCode StatusCode {
get; set; }
public TRetData Data {
get; set; }
public string Message {
get; set; }
}
/// <summary>
/// 第三方接口的基础类,方便校验、共用的参数继承
/// </summary>
public class ApilBase
{
}
/// <summary>
/// http请求
/// </summary>
/// <param name="url">url</param>
/// <param name="method">请求方法</param>
/// <param name="getDic">get请求入参</param>
/// <param name="postStr">post请求入参</param>
/// <param name="head">请求头入参</param>
/// <param name="contentType">报文类型</param>
/// <param name="timeout">超时时长(毫秒)</param>
/// <returns></returns>
public static HttpResponse HttpRequestAsync(string url, RequestMethod method, Dictionary<string, string> getDic = null, string postStr = "", Dictionary<string, string> head = null, string contentType