C#调用第三方API

这段代码展示了如何在C#中使用HttpWebRequest和HttpClient类进行HTTPPOST和GET请求,包括设置请求头、序列化JSON数据以及处理响应内容。示例中包含了无参数、带参数和带头部信息的API调用。
摘要由CSDN通过智能技术生成

1、调用webRequest / HttpClient

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
 
namespace CallWebApi
{
    /// <summary>
    /// 调用外部API
    /// </summary>
    public static class CallExternalAPI
    {
        /// <summary>
        /// WebRequest方式
        /// </summary>
        /// <returns></returns>
        public static string HttpPost(string url, Dictionary<string, object> body = null, Dictionary<string, string> header = null)
        {
            string result;
            try
            {
                Encoding encoding = Encoding.UTF8;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.Accept = "text/html, application/xhtml+xml, */*";
                request.ContentType = "application/json";
                if (header != null)
                {
                    foreach (var item in header)
                    {
                        request.Headers.Add(item.Key, item.Value);
                    }
                }
                if (body != null)
                {
                    byte[] buffer = encoding.GetBytes(JsonConvert.SerializeObject(body));
                    request.ContentLength = buffer.Length;
                    request.GetRequestStream().Write(buffer, 0, buffer.Length);
                }
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    return reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }
            return result;
        }
 
        /// <summary>
        /// HttpWebRequest方式
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string HttpGet(string url, Dictionary<string, string> header = null)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.ContentType = "application/json";
            if (header != null)
            {
                foreach (var item in header)
                {
                    request.Headers.Add(item.Key, item.Value);
                }
            }
 
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }
    }
}

2、调用

using System;
using System.Collections.Generic;
 
namespace CallWebApi
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("开始测试:");
 
            #region HttpWebRequest方式
            string result0 = CallExternalAPI.HttpPost("http://localhost:8500/api/employee/post-no");
            Console.WriteLine(result0);
 
            Dictionary<string, object> body1 = new Dictionary<string, object>
            {
                { "name", "12d" }
            };
            string result1 = CallExternalAPI.HttpPost("http://localhost:8500/api/employee/post", body1);
            Console.WriteLine(result1);
 
            Dictionary<string, string> header2 = new Dictionary<string, string>
            {
                { "token", "12d" }
            };
            Dictionary<string, object> body2 = new Dictionary<string, object>
            {
                { "name", "12d" }
            };
            string result2 = CallExternalAPI.HttpPost("http://localhost:8500/api/employee/post-token", body2, header2);
            Console.WriteLine(result2);
 
            string result3 = CallExternalAPI.HttpGet("http://localhost:8500/api/employee/list");
            Console.WriteLine(result3);
 
            string result4 = CallExternalAPI.HttpGet("http://localhost:8500/api/employee/get-yes?id=12");
            Console.WriteLine(result4);
 
            Dictionary<string, string> header5 = new Dictionary<string, string>
            {
                { "token", "12d" }
            };
            string result5 = CallExternalAPI.HttpGet("http://localhost:8500/api/employee/get?id=12", header5);
            Console.WriteLine(result5);
            #endregion
        }
    }
}
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值