【问题标题】:It is possible to send get/post requests with string and byte array parameters?可以使用字符串和字节数组参数发送 get/post 请求吗?
【发布时间】:2018-09-04 17:38:46
【问题描述】:

我必须使用多个参数向 Web 服务发送 POST 请求,其中一个参数具有 byte[] 类型。但我不知道如何传递 byte[] 参数。有人知道吗?另外,我想知道如何在 GET 请求中发送 byte[] 数组。任何帮助将不胜感激!

    using (var client = new WebClient())
    {
            var values = new NameValueCollection();
            values["thing1"] = "hello";
            values["thing2"] = "world"; // how to pass byte[] here?

            var response = client.UploadValues("http://www.example.com/recepticle.aspx", values);

            var responseString = Encoding.Default.GetString(response);
     }

或其他带有 HttpClient 的变体:

    private static readonly HttpClient client = new HttpClient();
    var values = new Dictionary<string, string>
    {
       { "thing1", "hello" },
       { "thing2", "world" } // how to pass byte[] here?
    };

    var content = new FormUrlEncodedContent(values);

    var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);

    var responseString = await response.Content.ReadAsStringAsync();

【问题讨论】:

  • 好吧,如果您使用的结构是字符串值,则不能传递 byte[] 数组...除非您使用 Base 64 对其进行编码。
  • 查看stackoverflow.com/a/23547930/3098521,看看它是否能回答您的问题。

标签: c# post get post-parameter


【解决方案1】:

你有几个选择:

  • 将请求的内容类型更改为二进制格式。这将排除包含任何字符串。
  • 使用multi-part format like RFC 1341
  • 对二进制数据进行编码,以便将其作为字符串发送。 Base64 很常见。

【讨论】:

    【解决方案2】:

    @Heretic Monkey 在 cmets 中说:好吧,如果您使用的结构是字符串值,则不能传递 byte[] 数组...除非您使用 Base 64

    也许在某些情况下你是对的,但是:

    Convert.ToBase64String 您可以使用 Convert.FromBase64String 轻松地将输出字符串转换回字节数组。 注意:输出字符串可以包含“+”、“/”和“=”。如果要在 URL 中使用字符串,则需要对其进行显式编码。 © combo_ci

    因此,有时最好使用 HttpServerUtility.UrlTokenEncode(byte[]) 并在服务器端对其进行解码。

    但我的问题是 Web 服务无法接受大文件。我得到的客户端异常是“415:不支持的媒体类型”。通过更改 Web 服务端的配置解决了它:

    <!-- To be added under <system.web> -->
    <httpRuntime targetFramework="4.5" maxRequestLength="1048576" executionTimeout="3600" />
    
    <!-- To be added under <system.webServer> -->
    <security>
    <requestFiltering>
    <requestLimits maxAllowedContentLength="1073741824" />
    </requestFiltering>
    </security>
    

    【讨论】:

      猜你喜欢
      • 2021-03-06
      • 2012-09-22
      • 1970-01-01
      • 2011-06-02
      • 2018-04-23
      • 2016-02-09
      • 1970-01-01
      • 1970-01-01
      • 2015-12-07
      相关资源
      最近更新 更多