網(wǎng)站首頁(yè) 編程語(yǔ)言 正文
一、概述
Net4.5以上的提供基本類,用于發(fā)送 HTTP 請(qǐng)求和接收來(lái)自通過(guò) URI 確認(rèn)的資源的 HTTP 響應(yīng)。
HttpClient是一個(gè)高級(jí) API,用于包裝其運(yùn)行的每個(gè)平臺(tái)上可用的較低級(jí)別功能。
// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();
static async Task Main()
{
// Call asynchronous network methods in a try/catch block to handle exceptions.
try
{
HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
// Above three lines can be replaced with new helper method below
// string responseBody = await client.GetStringAsync(uri);
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
二、HttpClient的使用
1.使用HttpClient調(diào)用Oauth的授權(quán)接口獲取access_token
1)OAuth使用的密碼式
2)獲取到access_token后才進(jìn)行下一步
2.帶著access_token調(diào)用接口
1)hearder上添加bearer方式的access_token
2)調(diào)用接口確保成功獲取到返回的結(jié)果
try
{
string host = ConfigurationManager.AppSettings["api_host"];
string username = ConfigurationManager.AppSettings["api_username"];
string password = ConfigurationManager.AppSettings["api_password"];
HttpClient httpClient = new HttpClient();
// 設(shè)置請(qǐng)求頭信息
httpClient.DefaultRequestHeaders.Add("Host", host);
httpClient.DefaultRequestHeaders.Add("Method", "Post");
httpClient.DefaultRequestHeaders.Add("KeepAlive", "false"); // HTTP KeepAlive設(shè)為false,防止HTTP連接保持
httpClient.DefaultRequestHeaders.Add("UserAgent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
//獲取token
var tokenResponse = httpClient.PostAsync("http://" + host + "/token", new FormUrlEncodedContent(new Dictionary<string, string> {
{"grant_type","password"},
{"username", username},
{"password", password}
}));
tokenResponse.Wait();
tokenResponse.Result.EnsureSuccessStatusCode();
var tokenRes = tokenResponse.Result.Content.ReadAsStringAsync();
tokenRes.Wait();
var token = Newtonsoft.Json.Linq.JObject.Parse(tokenRes.Result);
var access_token = token["access_token"].ToString();
// 調(diào)用接口發(fā)起POST請(qǐng)求
var authenticationHeaderValue = new AuthenticationHeaderValue("bearer", access_token);
httpClient.DefaultRequestHeaders.Authorization = authenticationHeaderValue;
var content = new StringContent(parameter);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = httpClient.PostAsync("http://" + host + "/" + api_address, content);
response.Wait();
response.Result.EnsureSuccessStatusCode();
var res = response.Result.Content.ReadAsStringAsync();
res.Wait();return Newtonsoft.Json.JsonConvert.DeserializeObject(res.Result);
}
catch (Exception ex)
{
return ResultEx.Init(ex.Message);
}
HttpClient 獲取圖片并保存到本機(jī)
class Program
{
static void Main()
{
//圖片路徑:https://img.infinitynewtab.com/wallpaper/1.jpg
string imgSourceURL = "https://img.infinitynewtab.com/wallpaper/";
DownloadImags(imgSourceURL).Wait();
}
private static async Task DownloadImags(string url)
{
var client = new HttpClient();
System.IO.FileStream fs;
int a = 1;
//文件名:序號(hào)+.jpg。可指定范圍,以下是獲取100.jpg~500.jpg.
for (int i = 100; i <= 500; i++)
{
var uri = new Uri(Uri.EscapeUriString(url+i.ToString()+".jpg"));
byte[] urlContents = await client.GetByteArrayAsync(uri);
fs = new System.IO.FileStream(AppDomain.CurrentDomain.BaseDirectory + "\\images\\"+ i.ToString() + ".jpg",System.IO.FileMode.CreateNew);
fs.Write(urlContents, 0, urlContents.Length);
Console.WriteLine(a++);
}
}
}
以下為封裝的類庫(kù)
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
public class HttpClientHelpClass
{
///
/// get請(qǐng)求
///
///
///
public static string GetResponse(string url, out string statusCode)
{
if (url.StartsWith("https"))
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = httpClient.GetAsync(url).Result;
statusCode = response.StatusCode.ToString();
if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
return result;
}
return null;
}
public static string RestfulGet(string url)
{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
return reader.ReadToEnd();
}
}
public static T GetResponse(string url)
where T : class, new()
{
if (url.StartsWith("https"))
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = httpClient.GetAsync(url).Result;
T result = default(T);
if (response.IsSuccessStatusCode)
{
Task<string> t = response.Content.ReadAsStringAsync();
string s = t.Result;
result = JsonConvert.DeserializeObject(s);
}
return result;
}
///
/// post請(qǐng)求
///
///
/// post數(shù)據(jù)
///
public static string PostResponse(string url, string postData, out string statusCode)
{
if (url.StartsWith("https"))
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
HttpContent httpContent = new StringContent(postData);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
httpContent.Headers.ContentType.CharSet = "utf-8";
HttpClient httpClient = new HttpClient();
//httpClient..setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
statusCode = response.StatusCode.ToString();
if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
return result;
}
return null;
}
///
/// 發(fā)起post請(qǐng)求
///
///
/// url
/// post數(shù)據(jù)
///
public static T PostResponse(string url, string postData)
where T : class, new()
{
if (url.StartsWith("https"))
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
HttpContent httpContent = new StringContent(postData);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpClient httpClient = new HttpClient();
T result = default(T);
HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
if (response.IsSuccessStatusCode)
{
Task<string> t = response.Content.ReadAsStringAsync();
string s = t.Result;
result = JsonConvert.DeserializeObject(s);
}
return result;
}
///
/// 反序列化Xml
///
///
///
///
public static T XmlDeserialize(string xmlString)
where T : class, new()
{
try
{
XmlSerializer ser = new XmlSerializer(typeof(T));
using (StringReader reader = new StringReader(xmlString))
{
return (T)ser.Deserialize(reader);
}
}
catch (Exception ex)
{
throw new Exception("XmlDeserialize發(fā)生異常:xmlString:" + xmlString + "異常信息:" + ex.Message);
}
}
public static string PostResponse(string url, string postData, string token, string appId, string serviceURL, out string statusCode)
{
if (url.StartsWith("https"))
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
HttpContent httpContent = new StringContent(postData);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
httpContent.Headers.ContentType.CharSet = "utf-8";
httpContent.Headers.Add("token", token);
httpContent.Headers.Add("appId", appId);
httpContent.Headers.Add("serviceURL", serviceURL);
HttpClient httpClient = new HttpClient();
//httpClient..setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
statusCode = response.StatusCode.ToString();
if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
return result;
}
return null;
}
///
/// 修改API
///
///
///
///
public static string KongPatchResponse(string url, string postData)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "PATCH";
byte[] btBodys = Encoding.UTF8.GetBytes(postData);
httpWebRequest.ContentLength = btBodys.Length;
httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
var streamReader = new StreamReader(httpWebResponse.GetResponseStream());
string responseContent = streamReader.ReadToEnd();
httpWebResponse.Close();
streamReader.Close();
httpWebRequest.Abort();
httpWebResponse.Close();
return responseContent;
}
///
/// 創(chuàng)建API
///
///
///
///
public static string KongAddResponse(string url, string postData)
{
if (url.StartsWith("https"))
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
HttpContent httpContent = new StringContent(postData);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded") { CharSet = "utf-8" };
var httpClient = new HttpClient();
HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
return result;
}
return null;
}
///
/// 刪除API
///
///
///
public static bool KongDeleteResponse(string url)
{
if (url.StartsWith("https"))
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
var httpClient = new HttpClient();
HttpResponseMessage response = httpClient.DeleteAsync(url).Result;
return response.IsSuccessStatusCode;
}
///
/// 修改或者更改API? ?
///
///
///
///
public static string KongPutResponse(string url, string postData)
{
if (url.StartsWith("https"))
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
HttpContent httpContent = new StringContent(postData);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded") { CharSet = "utf-8" };
var httpClient = new HttpClient();
HttpResponseMessage response = httpClient.PutAsync(url, httpContent).Result;
if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
return result;
}
return null;
}
///
/// 檢索API
///
///
///
public static string KongSerchResponse(string url)
{
if (url.StartsWith("https"))
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
var httpClient = new HttpClient();
HttpResponseMessage response = httpClient.GetAsync(url).Result;
if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
return result;
}
return null;
}
}
原文鏈接:https://www.cnblogs.com/springsnow/p/11700341.html
相關(guān)推薦
- 2023-04-19 微信小程序授權(quán)登錄三種實(shí)現(xiàn)方式
- 2023-10-09 時(shí)間戳轉(zhuǎn)日期格式-自動(dòng)補(bǔ)零,日期格式轉(zhuǎn)時(shí)間戳
- 2022-07-06 Python中的字符串相似度_python
- 2022-07-30 react擴(kuò)展6_renderProps
- 2022-07-11 Python利用xlrd?與?xlwt?模塊操作?Excel_python
- 2022-05-02 在kali上安裝AWVS的圖文教程_相關(guān)技巧
- 2022-09-24 一文詳解go?mod依賴管理詳情_(kāi)Golang
- 2022-07-12 C語(yǔ)言中常見(jiàn)字符串API詳解
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過(guò)濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支