WebRequest方式
- 封装的方法
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();
}
}
}
}
- 调用方式using Newtonsoft.Json;
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
}
}
}
HttpClient方式
- 封装的方法
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace CallWebApi
{
/// <summary>
/// HttpClient方式
/// </summary>
public static class HttpClientHelper
{
public static HttpClient HttpClient { get; set; }
static HttpClientHelper()
{
//单例模式
if (HttpClient == null)
{
HttpClient = new HttpClient();
}
HttpClient.DefaultRequestHeaders.Accept.Clear();
HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//能解读https类型
//ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
}
/// <summary>
/// Get方法
/// </summary>
/// <param name="url">目标链接(含参数)</param>
/// <returns>返回的字符串</returns>
public static async Task<string> GetAsync(string url, Dictionary<string, string> header = null)
{
if (header != null)
{
foreach (var item in header)
{
HttpClient.DefaultRequestHeaders.Add(item.Key, item.Value);
}
}
using (HttpResponseMessage response = await HttpClient.GetAsync(url))
{
response.EnsureSuccessStatusCode();
string result = await response.Content.ReadAsStringAsync();
return result;
}
}
/// <summary>
/// Post方法
/// </summary>
/// <param name="url">目标链接</param>
/// <param name="body"></param>
/// <param name="header"></param>
/// <returns>返回的字符串</returns>
public static async Task<string> PostAsync(string url, Dictionary<string, object> body = null, Dictionary<string, string> header = null)
{
if (header != null)
{
foreach (var item in header)
{
HttpClient.DefaultRequestHeaders.Add(item.Key, item.Value);
}
}
StringContent content = new StringContent(JsonConvert.SerializeObject(body));
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
using (HttpResponseMessage response = await HttpClient.PostAsync(url, content))
{
response.EnsureSuccessStatusCode();
string result = await response.Content.ReadAsStringAsync();
return result;
}
}
/// <summary>
/// Post方法
/// </summary>
/// <param name="url">目标链接</param>
/// <param name="json">发送的json格式的参数字符串</param>
/// <returns>返回的字符串</returns>
public static async Task<string> PostAsync(string url, HttpContent content)
{
//HttpContent content = new FormUrlEncodedContent(new Dictionary<string, string>()
// {
// { "token", token},
// { "orderNo", orderNo}
// });
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded") { CharSet = "utf-8" };
using (HttpResponseMessage response = await HttpClient.PostAsync(url, content))
{
response.EnsureSuccessStatusCode();
string result = await response.Content.ReadAsStringAsync();
return result;
}
}
}
}
- 调用方式
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace CallWebApi
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("开始测试:");
string result0 = HttpClientHelper.PostAsync("http://localhost:8500/api/employee/post-no").Result;
Console.WriteLine(result0);
Dictionary<string, object> body1 = new Dictionary<string, object>
{
{ "name", "12d" }
};
string result1 = HttpClientHelper.PostAsync("http://localhost:8500/api/employee/post", body1).Result;
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 = HttpClientHelper.PostAsync("http://localhost:8500/api/employee/post-token", body2, header2).Result;
Console.WriteLine(result2);
string result3 = HttpClientHelper.GetAsync("http://localhost:8500/api/employee/list").Result;
Console.WriteLine(result3);
string result4 = HttpClientHelper.GetAsync("http://localhost:8500/api/employee/get-yes?id=12").Result;
Console.WriteLine(result4);
Dictionary<string, string> header5 = new Dictionary<string, string>
{
{ "token", "12d" }
};
string result5 = HttpClientHelper.GetAsync("http://localhost:8500/api/employee/get?id=12", header5).Result;
Console.WriteLine(result5);
}
}
}