溫馨提示×

c# webclient怎樣發送請求

c#
小樊
142
2024-12-02 16:30:52
欄目: 編程語言

在C#中,您可以使用WebClient類來發送HTTP請求。以下是一個簡單的示例,展示了如何使用WebClient發送GET和POST請求:

using System;
using System.Net;
using System.IO;

namespace WebClientExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // 發送GET請求
            string getResponse = SendGetRequest("https://api.example.com/data");
            Console.WriteLine("GET Response: " + getResponse);

            // 發送POST請求
            string postData = "key1=value1&key2=value2";
            string postResponse = SendPostRequest("https://api.example.com/data", postData);
            Console.WriteLine("POST Response: " + postResponse);
        }

        static string SendGetRequest(string url)
        {
            using (WebClient webClient = new WebClient())
            {
                return webClient.DownloadString(url);
            }
        }

        static string SendPostRequest(string url, string data)
        {
            using (WebClient webClient = new WebClient())
            {
                byte[] dataBytes = Encoding.UTF8.GetBytes(data);
                webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                return webClient.UploadString(url, dataBytes);
            }
        }
    }
}

在這個示例中,我們定義了兩個方法:SendGetRequestSendPostRequest。SendGetRequest方法接受一個URL參數,并使用WebClientDownloadString方法發送GET請求。SendPostRequest方法接受一個URL和一個數據字符串參數,將數據字符串轉換為字節數組,并設置內容類型為application/x-www-form-urlencoded,然后使用WebClientUploadString方法發送POST請求。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女