Search code examples
c#postgetpost-parameter

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


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

Solution

  • @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>