2022年2月26日 星期六

[研究][ASP.NET WebForm C#]WebClient 呼叫 Web API、REST/RESTful API 測試

[研究][ASP.NET WebForm C#]WebClient 呼叫 Web API、REST/RESTful API 測試

2022-02-26

Visual Studio2022 v17.1.0 + ASP.NET + C# + Web Application + WebForm

Default.aspx


<%@ Page Language="C#" 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" />
        </div>
    </form>
    <asp:Label ID="Label_MSG1" runat="server" Text="Label"></asp:Label>
</body>
</html>

Default.aspx.cs


using System;
using System.Net;
using System.Text;

namespace WebApplication1
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            WebClient client = new WebClient();
            client.Encoding = Encoding.UTF8;
            client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";

            string response;
            string account = "帳號;
            string password = "密碼";

            try
            {
                response = client.UploadString("https://網址/rest/verify",
                "account=" + account + "&pass=" + password);
            }
            catch
            {
                Label_MSG1.Text = "fail";
                return;
            }
            Label_MSG1.Text = response; // JSON Format Data
        }
    }
}

後來發現

WebRequest、WebClient 和 >servicepoint 已淘汰
https://docs.microsoft.com/zh-tw/dotnet/core/compatibility/networking/6.0/webrequest-deprecated
請改用 System.Net.Http.HttpClient 類別。

(完)

相關

[研究][ASP.NET WebForm C#]HttpClient 呼叫 Web API、REST/RESTful API 測試(二)
https://shaurong.blogspot.com/2022/02/aspnet-webform-chttpclient-web_26.html

[研究][ASP.NET WebForm C#]HttpClient 呼叫 Web API、REST/RESTful API 測試(一)
http://shaurong.blogspot.com/2022/02/aspnet-webform-chttpclient-web.html

[研究][ASP.NET WebForm C#]WebClient 呼叫 Web API、REST/RESTful API 測試https://shaurong.blogspot.com/2022/02/aspnet-webform-cwebclient-web.html


沒有留言:

張貼留言