溫馨提示×

c# httpwebrequest如何處理響應(yīng)

c#
小樊
82
2024-11-16 20:33:52
欄目: 編程語言

在C#中,使用HttpWebRequest類處理HTTP響應(yīng)主要包括以下步驟:

  1. 創(chuàng)建一個HttpWebRequest實例:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.example.com/data");
  1. 設(shè)置請求屬性(可選):
request.Method = "GET"; // 或者 "POST"
request.ContentType = "application/json";
request.Timeout = 10000; // 設(shè)置超時時間(毫秒)
  1. 發(fā)送請求并獲取響應(yīng):
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    // 處理響應(yīng)的代碼將在這里
}
  1. 讀取響應(yīng)內(nèi)容(可選):
using (Stream responseStream = response.GetResponseStream())
{
    using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8))
    {
        string responseText = reader.ReadToEnd();
        // 處理響應(yīng)文本的代碼將在這里
    }
}

下面是一個完整的示例:

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

class Program
{
    static void Main()
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.example.com/data");
        request.Method = "GET";
        request.ContentType = "application/json";
        request.Timeout = 10000;

        try
        {
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                Console.WriteLine("HTTP狀態(tài)碼: " + response.StatusCode);
                Console.WriteLine("HTTP狀態(tài)描述: " + response.StatusDescription);

                using (Stream responseStream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8))
                    {
                        string responseText = reader.ReadToEnd();
                        Console.WriteLine("響應(yīng)內(nèi)容: " + responseText);
                    }
                }
            }
        }
        catch (WebException ex)
        {
            Console.WriteLine("請求發(fā)生錯誤: " + ex.Message);
        }
    }
}

這個示例展示了如何使用HttpWebRequest類發(fā)送一個GET請求,獲取響應(yīng),并輸出HTTP狀態(tài)碼和響應(yīng)內(nèi)容。你可以根據(jù)實際需求修改這個示例,例如使用POST方法發(fā)送數(shù)據(jù)或處理異常。

0