You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用HttpWebRequest调用WooCommerce v3 API返回401未授权如何解决

问题根因

HttpWebRequest 不会自动解析 URL 中携带的用户名:密码格式的基础认证(Basic Auth)凭证,浏览器、Postman 会自动提取该部分内容生成对应的 Authorization 请求头,但是你的代码中请求发送时没有携带该认证头,因此服务端返回 401 未授权错误。

修复方案

方案1:直接修改现有 HttpWebRequest 代码

手动为请求添加 Basic Auth 头,注意将 URL 中原有的用户名密码移除,避免产生冗余参数:

// 移除URL中的站点用户名密码,保留WooCommerce接口参数
string wc_url = "https://mydomain.com/wp-json/wc/v3/products?consumer_key=ck_12345678901234567890&consumer_secret=cs_12345678901234567890";
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(wc_url);
httpWebRequest.AllowReadStreamBuffering = false;

// 构造Basic Auth认证头
string siteUsername = "MyUsername";
string sitePassword = "MyPassword";
string authCredential = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes($"{siteUsername}:{sitePassword}"));
httpWebRequest.Headers.Add("Authorization", $"Basic {authCredential}");

WebResponse wr = await httpWebRequest.GetResponseAsync().ConfigureAwait(false);

方案2(推荐):使用 HttpClient 实现请求

HttpWebRequest 属于 .NET 早期遗留 API,微软官方已推荐新代码使用 HttpClient 实现HTTP请求,示例代码如下:

// HttpClient建议全局静态实例化,避免重复创建产生套接字资源消耗问题
private static readonly HttpClient _wcClient = new HttpClient();

public async Task<string> GetWooCommerceProductsAsync()
{
    // 设置站点Basic Auth认证
    string siteUsername = "MyUsername";
    string sitePassword = "MyPassword";
    string authCredential = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes($"{siteUsername}:{sitePassword}"));
    _wcClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", authCredential);

    string requestUrl = "https://mydomain.com/wp-json/wc/v3/products?consumer_key=ck_12345678901234567890&consumer_secret=cs_12345678901234567890";
    using var response = await _wcClient.GetAsync(requestUrl);
    // 校验请求状态,非200状态码会直接抛出异常
    response.EnsureSuccessStatusCode();
    // 返回JSON格式的商品数据
    return await response.Content.ReadAsStringAsync();
}

内容的提问来源于stack exchange,提问作者Y U

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 00:24:02