呼叫第三方 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 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();
}
}
static HttpClient 或 IHttpClientFactory。Timeout (整體) + ReadWriteTimeout (讀寫),防止掛起。AutomaticDecompression 減少頻寬。掌握底層 HttpWebRequest 細節有助於除錯舊專案,新專案建議直接使用 HttpClient / IHttpClientFactory 享受更現代的 API 與 DI 整合。