[研究][ASP.NET]用 HttpClient 做 RESTful API 呼叫
2023-03-02
環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C#
HttpClient 類別 (System.Net.Http) | Microsoft Learn
https://learn.microsoft.com/zh-tw/dotnet/api/system.net.http.httpclient?view=netframework-4.8
********************************************************************************
Default.aspx
<%@ Page Language="C#" Async="true" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /><br />
<asp:Label ID="Label1" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
|
注意,Page 要多加上 Async="true",否則會有下面錯誤
非同步作業目前無法開始。非同步作業只有在非同步處理常式或模組或是頁面生命週期中特定事件期間中才能開始。如果執行頁面時發生此例外狀況,請確認頁面已標示為 <%@ Page Async="true" %>。此例外狀況也可能表示嘗試呼叫一般在 ASP.NET 要求處理中不支援的 "async void" 方法。相反地,非同步方法應傳回工作而呼叫端應等候它。
********************************************************************************
Default.aspx.cs
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication6 { public class GetObjectResult { public string message { get; set; } public string describe { get; set; } public List<GetObjectData> data { get; set; } } public class GetObjectData { public string product_class { get; set; } public string product_name { get; set; } public string product_status { get; set; } public string product_attri { get; set; } public string product_level { get; set; } public string product_type { get; set; } } public partial class Default : System.Web.UI.Page { protected async void Page_Load(object sender, EventArgs e) { } protected async void Button1_Click(object sender, EventArgs e) { // 建立 HttpClient 實例 HttpClient client = new HttpClient(); try { // 呼叫 API 的 URL string url = "https://XXX.XXX.XXX/getObjectList"; // 建立要傳送的資料 var data = new Dictionary<string, string> { { "code", "帳號" }, { "pass", "密碼" } }; // 建立要傳送的內容 var content = new FormUrlEncodedContent(data); // 呼叫 API,取得回應 HttpResponseMessage response = await client.PostAsync(url, content); // 檢查回應是否成功 if (response.IsSuccessStatusCode) { // 取得回應內容 string responseContent = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject<GetObjectResult>(responseContent); // 在頁面上顯示回應內容 //Response.Write(responseContent); //OK Response.Write(result.message); Response.Write(result.describe); foreach( var dd in result.data) { Response.Write(dd.product_name +"," + dd.product_level + "<br />"); } } else { // 在頁面上顯示錯誤訊息 Response.Write("Error: " + response.StatusCode); } } catch (Exception ex) { // 在頁面上顯示錯誤訊息 Response.Write("Error: " + ex.Message); } } } } |
這是一個實際測試過,真實可用的 Code,只是帳號、密碼、資料、網址做了些變更。
(完)
相關
[研究][ASP.NET]用 HttpClientFactory 做 RESTful API 呼叫
https://shaurong.blogspot.com/2023/03/aspnet-httpclientfactory-restful-api.html
[研究]ASP.NET RESTful API: 比較 HTTPClient , RestSharp , WebClient, HttpClientFactory, Flurl, Refit, RestEase
https://shaurong.blogspot.com/2023/03/aspnet-restful-api-httpclient-restsharp.html
[研究][ASP.NET]RestSharp 106 升級 v107疑難排解:未包含 HasValue 的定義
https://shaurong.blogspot.com/2023/03/aspnetrestsharp-106-v107-hasvalue.html
[研究][ASP.NET]用 RestSharp v107 做 RESTful API 呼叫
https://shaurong.blogspot.com/2023/03/aspnet-restsharp-v107-restful-api.html
[研究][ASP.NET]用 HttpClient 做 RESTful API 呼叫
https://shaurong.blogspot.com/2023/03/aspnet-httpclient-restful-api.html
[研究][ASP.NET]ChatGPT,請提供完整 RestSharp v107 範例程式https://shaurong.blogspot.com/2023/03/aspnetchatgpt-restsharp-v107.html
沒有留言:
張貼留言