是否可以发送带有字符串和字节数组参数的获取/发布请求?



我必须向具有多个参数的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();

您有以下几种选择:

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

@Heretic Monkey 在评论中说: 好吧,如果你使用的结构是字符串值的,你就不能传递 byte[] 数组......除非你以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>

最新更新