0

I have to send POST request to web service with multiple parameters where one of them has byte[] type. But I dont know how to pass byte[] parameter. Does anybody know? Also, I would like to know how to send byte[] array in GET requests. Any help will be appreciated!

    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);
     }

or another variant with 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();
fr0ga
  • 333
  • 4
  • 9

2 Answers2

1

You have a few choices:

  • Change the content-type of your request to a binary format. This would preclude including any strings.
  • Use a multi-part format like RFC 1341
  • Encode your binary data so it can be sent as a string. Base64 is common.
John Wu
  • 50,556
  • 8
  • 44
  • 80
0

@Heretic Monkey said in comments: Well, you can't pass a byte[] array if the structure you're using is string valued... unless you Base 64

Maybe in some cases you are right but:

Convert.ToBase64String You can easily convert the output string back to byte array by using Convert.FromBase64String. Note: The output string could contain '+', '/' and '='. If you want to use the string in a URL, you need to explicitly encode it. © combo_ci

So, sometimes it is better to use HttpServerUtility.UrlTokenEncode(byte[]) and decode it on server side.

But my problem was that web service could not accept large files. And the exception on client side that I got was "415: Unsupported Media Type". It was solved by changing config on the web service side:

<!-- 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>
fr0ga
  • 333
  • 4
  • 9