【问题标题】:How to simulate HTTP POST programatically to send file and input parameters [duplicate]如何以编程方式模拟 HTTP POST 以发送文件和输入参数 [重复]
【发布时间】:2015-01-14 06:08:42
【问题描述】:

我需要POST HTML 表单以编程方式 包含一些输入参数和一个带有 ContentType=application/zip 的 zip 文件。

<form id="form1" method="post" action="http://subdomain.domain.com/" runat="server"  enctype="multipart/form-data">
<div>
    <input type="file" id="file" name="file" value=""  />
    <input type="text" name="param1" value="valparam1" />
    <input type="text" name="param2" value="valparam2" />
    <input type="text" name="param3" value="valparam3" />
    <input id="Submit1" type="submit" value="Send"/>
</div>

简而言之,我想以编程方式模拟上述行为(同时发布文件 ContentType)。

我更喜欢 WebClient 而不是 HttpRequest;

【问题讨论】:

  • @Tarik,我查看了您提供的链接,但就我而言,我还想上传具有特定 ContentType 的文件。

标签: c# .net post


【解决方案1】:

不完全是,但您需要这样的东西(我参与的项目之一的示例),您可以根据您的要求进行更改。

    string url = "Your url";
    var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
    httpWebRequest.Method = "POST";
    httpWebRequest.ContentType = "application/json";

    List<string> values = new List<string>();
    values.Add(groupValue);

    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {

        string json = new JavaScriptSerializer().Serialize(new
        {
            apikey = apiKey,
            id = listId,
            name = groupName,
            type = "radio",
            groups = values

        });

        streamWriter.Write(json);
        streamWriter.Flush();
        streamWriter.Close();

        var response = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(response.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            var grouping = new JavaScriptSerializer().Deserialize(result, typeof(MailchimpGrouping));
            if (grouping != null)
            {
                return (grouping as MailchimpGrouping).Id;
            }
        }

    }
    return 0;

}

【讨论】:

  • 感谢您的回答。就我而言,我还想上传带有特定 ContentType=application/zip 的文件。在您的 sn-p 中,请求是 JSON,但在我的情况下,它应该是表单提交,并且当服务器端使用 Request.Files[0].ContentType 进行检查时,文件 ContentType 应该是“applicaiton/zip”
猜你喜欢
  • 1970-01-01
  • 2011-08-21
  • 1970-01-01
  • 2014-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-20
  • 1970-01-01
相关资源
最近更新 更多