萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET 以 HttpWebRequest 實作 POST 送出表單資料並取得回應

呼叫第三方 API、串接支付閘道、推送通知等場景,常需在伺服端以 HTTP POST 送出 application/x-www-form-urlencoded 表單資料並解析 JSON/XML 回應。本文提供可直接生產使用的泛型輔助方法,涵蓋編碼、逾時、例外處理、回應流釋放等細節。

核心輔助方法

public static class HttpHelper {
    /// 
    /// 發送 POST 表單並回傳原始回應字串
    /// 
    public static string PostForm(string url, IDictionary<string, string> formData, Encoding encoding = null, int timeoutMs = 30000) {
        encoding = encoding ?? Encoding.UTF8;
        string postData = string.Join("&", formData.Select(kvp => $"{Uri.EscapeDataString(kvp.Key)}={Uri.EscapeDataString(kvp.Value)}"));
        byte[] bytes = encoding.GetBytes(postData);

        var request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = bytes.Length;
        request.Timeout = timeoutMs;
        request.ReadWriteTimeout = timeoutMs * 2;
        request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
        request.UserAgent = "Mozilla/5.0 (compatible; ASP.NET HttpHelper)";

        using (var reqStream = request.GetRequestStream()) {
            reqStream.Write(bytes, 0, bytes.Length);
        }

        try {
            using (var response = (HttpWebResponse)request.GetResponse())
            using (var respStream = response.GetResponseStream())
            using (var reader = new StreamReader(respStream, encoding)) {
                return reader.ReadToEnd();
            }
        } catch (WebException ex) {
            using (var resp = ex.Response as HttpWebResponse)
            using (var stream = resp?.GetResponseStream())
            using (var reader = stream != null ? new StreamReader(stream, encoding) : null) {
                string errBody = reader?.ReadToEnd() ?? ex.Message;
                throw new HttpRequestException($"HTTP {(int?)resp?.StatusCode} {resp?.StatusCode}: {errBody}", ex);
            }
        }
    }

    /// 
    /// 發送 POST 並自動反序列化 JSON 回應
    /// 
    public static T PostFormJson<T>(string url, IDictionary<string, string> formData, Encoding encoding = null, int timeoutMs = 30000) {
        string json = PostForm(url, formData, encoding, timeoutMs);
        return JsonConvert.DeserializeObject<T>(json);
    }
}

使用範例

var form = new Dictionary<string, string> {
    ["grant_type"] = "client_credentials",
    ["client_id"] = "abc123",
    ["client_secret"] = "secret",
    ["scope"] = "api.read"
};

try {
    var tokenResp = HttpHelper.PostFormJson<TokenResponse>("https://api.example.com/oauth/token", form);
    Console.WriteLine($"AccessToken: {tokenResp.AccessToken}, ExpiresIn: {tokenResp.ExpiresIn}");
} catch (HttpRequestException ex) {
    Log.Error(ex, "取得 Token 失敗");
    // 處理重試、告警等
}

進階:支援檔案上傳 (multipart/form-data)

若需上傳檔案,需手動組裝 multipart body,建議改用 HttpClient + MultipartFormDataContent (.NET 4.5+),代碼更簡潔:

using (var client = new HttpClient()) {
    using (var content = new MultipartFormDataContent()) {
        content.Add(new StringContent("value1"), "field1");
        var fileBytes = File.ReadAllBytes(@"C:\temp\test.pdf");
        content.Add(new ByteArrayContent(fileBytes), "file", "test.pdf");
        var resp = await client.PostAsync("https://api.example.com/upload", content);
        resp.EnsureSuccessStatusCode();
        string json = await resp.Content.ReadAsStringAsync();
    }
}

效能與穩定性建議

  • 重用 HttpClient:避免頻繁建立/銷毀導致 Socket 耗盡 (TIME_WAIT),改用 static HttpClient 或 IHttpClientFactory。
  • 設定逾時:Timeout (整體) + ReadWriteTimeout (讀寫),防止掛起。
  • 啟用自動解壓:AutomaticDecompression 減少頻寬。
  • 記錄請求/回應:生產環境記錄 URL、耗時、狀態碼、錯誤訊息,便於事後追查。
  • 重試策略:對 5xx、408、網路錯誤實作指數退避重試 (Polly 庫)。

掌握底層 HttpWebRequest 細節有助於除錯舊專案,新專案建議直接使用 HttpClient / IHttpClientFactory 享受更現代的 API 與 DI 整合。

copyright © 萬盛學電腦網 all rights reserved