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

如何用C#代码向指定URL提交游客信息POST请求?

C# 实现游客信息POST提交到指定API

基于你提供的示例代码修改

你给出的示例里使用了自定义的MyWebRequest类,只需替换请求数据即可完成需求:

static void Main(string[] args)
{
    // 构造符合要求的POST请求数据
    string data = "tourist_name=dummy&tourist_email=test123@test.com&tourist_location=Paris";
    MyWebRequest myRequest = new MyWebRequest("http://restapi.adequateshop.com/api/Tourist", "POST", data);
    // 获取并输出响应结果
    string response = myRequest.GetResponse();
    Console.WriteLine(response);
}

使用.NET标准库HttpClient实现(更推荐)

如果没有自定义的MyWebRequest类,推荐使用.NET内置的HttpClient来完成请求,这是官方推荐的HTTP请求方式:

完整代码示例

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        // 创建HttpClient实例(建议全局复用,避免频繁创建)
        using var httpClient = new HttpClient();
        
        // 构造表单格式的请求数据
        var formData = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("tourist_name", "dummy"),
            new KeyValuePair<string, string>("tourist_email", "test123@test.com"),
            new KeyValuePair<string, string>("tourist_location", "Paris")
        });
        
        // 发送POST请求并获取响应
        var response = await httpClient.PostAsync("http://restapi.adequateshop.com/api/Tourist", formData);
        
        // 确保请求成功(状态码为2xx)
        response.EnsureSuccessStatusCode();
        
        // 读取并输出响应内容
        string responseContent = await response.Content.ReadAsStringAsync();
        Console.WriteLine(responseContent);
    }
}

关键说明

  • FormUrlEncodedContent用于构造application/x-www-form-urlencoded格式的请求体,和示例代码的数据格式完全匹配
  • 使用async/await是.NET异步编程的标准方式,可避免阻塞主线程
  • EnsureSuccessStatusCode会在HTTP状态码非2xx时抛出异常,便于快速定位请求错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 05:06:02