0

我必须使用多个参数向 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();
4

2 回答 2

1

你有几个选择:

  • 将请求的内容类型更改为二进制格式。这将排除包括任何字符串。
  • 使用多部分格式,如 RFC 1341
  • 对二进制数据进行编码,使其可以作为字符串发送。Base64很常见。
于 2018-09-04T18:01:28.520 回答
0

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

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

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

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

但我的问题是网络服务不能接受大文件。我得到的客户端异常是“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>
于 2018-09-10T13:35:48.647 回答