簡體   English   中英

是否可以使用字符串和字節數組參數發送get / post請求?

[英]It is possible to send get/post requests with string and byte array parameters?

我必須使用多個參數將POST請求發送到Web服務,其中之一具有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 []數組...除非您使用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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM