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

如何在C#中用WebRequest类处理LOB.com明信片API请求并获取JSON响应

用C#的HttpWebRequest实现LOB.com API请求获取明信片信息

我来帮你把LOB提供的curl请求转换成完整的C# HttpWebRequest代码,你之前的代码已经搭好了基础框架,核心是要补上Basic身份验证的部分(因为curl里的-u参数就是做这个的),以及响应读取的逻辑。

完整实现代码

using System;
using System.IO;
using System.Net;
using System.Text;
// 如果用Newtonsoft.Json的话需要先安装NuGet包:Install-Package Newtonsoft.Json
using Newtonsoft.Json;

class LobPostcardRequest
{
    static void Main()
    {
        // 替换成你的API密钥和目标明信片ID
        string apiKey = "test_0dc8d51e0acffcb1880e0f19c79b2f5b0cc";
        string postcardId = "psc_95d1eafeb5b9a766";
        string apiUrl = $"https://api.lob.com/v1/postcards/{postcardId}";

        var httpWebRequest = (HttpWebRequest)WebRequest.Create(apiUrl);
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Accept = "*/*";
        httpWebRequest.Method = "GET";

        // 添加Basic身份验证头——这是curl -u参数的核心逻辑
        string authInfo = $"{apiKey}:"; // LOB API只需要API密钥作为用户名,密码留空即可
        authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
        httpWebRequest.Headers["Authorization"] = $"Basic {authInfo}";

        try
        {
            // 发送请求并读取响应
            using (var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
            using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
            {
                string jsonResponse = streamReader.ReadToEnd();
                Console.WriteLine("JSON响应内容:");
                Console.WriteLine(jsonResponse);

                // 可选:将JSON反序列化成强类型对象(需先定义对应实体类)
                // Postcard postcard = JsonConvert.DeserializeObject<Postcard>(jsonResponse);
                // Console.WriteLine($"明信片状态:{postcard.Status}");
            }
        }
        catch (WebException ex)
        {
            // 捕获并处理API错误(比如密钥无效、明信片不存在等)
            using (var errorResponse = (HttpWebResponse)ex.Response)
            using (var streamReader = new StreamReader(errorResponse.GetResponseStream()))
            {
                string errorJson = streamReader.ReadToEnd();
                Console.WriteLine("请求出错:");
                Console.WriteLine(errorJson);
            }
        }
    }
}

// 示例实体类,可根据LOB API返回的JSON结构调整字段
public class Postcard
{
    public string Id { get; set; }
    public string Status { get; set; }
    // 其他字段如收件人信息、尺寸等可按需添加
}

关键细节说明

  • 身份验证逻辑:curl的-u参数本质就是Basic认证,我们把API密钥和空密码组合成{apiKey}:的格式,转成Base64编码后放到Authorization请求头里,和curl的行为完全一致。
  • 响应读取:通过StreamReader读取响应流,直接得到完整的JSON字符串,方便后续使用。
  • 错误处理:添加了WebException捕获,能获取API返回的错误详情(比如401未授权、404资源不存在等),便于调试。
  • JSON解析:如果需要结构化处理数据,可以用Newtonsoft.Json或者.NET自带的System.Text.Json,只需要定义和API返回结构匹配的实体类即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:42:43