C# 封装对第三方接口的调用

本文介绍如何使用C#封装JSON格式的HTTP第三方接口,通过反射、HttpWebRequest、泛型类和Newtonsoft.Json库,实现入参和出参的便捷转换,提高代码复用性和接口管理效率。虽然在接口数量较大时可能影响速度,但适用于日常开发需求。
摘要由CSDN通过智能技术生成

引言
在日常开发中经常会对接第三方接口,所以经常需要封装第三方接口,方便在程序中使用,本文主要是封装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 
  • 0
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值