Xamarin.Android: HttpClient with MultipartFormDataContent returns 400 Bad Request

Pierre-ChristopheDusPierre-ChristopheDus FRUniversity ✭✭✭

Hello,

I develop a Xamarin.Android app and I need to update an audio recorded file.

For this, my client has provided me an API like this:

  • URL: /api/recordings/
  • Method: POST
  • Data format: multipart/form-data
  • Fields: some text fields and the audio file to send

When I test it on Postman, it works fine. The generate code snippets are:

POST /api/recordings/ HTTP/1.1
Host: X.X.X.X
Cache-Control: no-cache
Postman-Token: xxxxx-xxxx-xxxx-xxxx-xxxxx
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="param1" 
param1 name

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="param2"
param2 name

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="audio_file"; filename="xxx.wav"
Content-Type: audio/wav

But when I try from the app, I get an 400 - Bad Request error.

First attempt:

I first tried with the following basic code:

using (HttpClient client = new HttpClient())
{       
    try
    {
        MultipartFormDataContent formData = new MultipartFormDataContent();
        formData.Add(new StringContent("param1 name"), "param1");
        formData.Add(new StringContent("param2 name"), "param2");
        var response = await client.PostAsync(url, formData);
        Logger.Log("Response : " + responseObj.ToString());
    }
    catch (Exception ex)
    {
        Logger.Log("Exception : " + ex.ToString());
    }
}

But there is a 400 - Bad Request error:

Response : StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Server: nginx/1.15.0
  Date: Mon, 25 Jun 2018 23:25:41 GMT
  Connection: keep-alive
  Vary: Cookie
  X-Frame-Options: SAMEORIGIN
  Content-Type: application/json
  Content-Length: 85
  Allow: POST, OPTIONS
}

Second attempt:

Then I've tried the following snippet that I found there:

string servResp = "";
string boundary = "----CustomBoundary" + DateTime.Now.Ticks.ToString("x");
using (var content = new MultipartFormDataContent(boundary))
{
    content.Headers.Remove("Content-Type");
    content.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary);
    content.Add(new StringContent("param1 name"), "param1");
    content.Add(new StringContent("param2 name"), "param2");

    HttpClientHandler handler = new HttpClientHandler();
    var cookieContainer = new CookieContainer();
    handler.CookieContainer = cookieContainer;

    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
    request.Headers.ExpectContinue = false;
    request.Content = content;
    try
    {
        var httpClient = new HttpClient(handler);
        HttpResponseMessage response = await httpClient.SendAsync(request);
        response.EnsureSuccessStatusCode();
        servResp = await response.Content.ReadAsStringAsync();
    }
    catch (Exception ex)
    {
        Logger.Log("PostTest() - Exception : " + ex.ToString());
    }
}
return servResp;

But there is still a 400 - Bad Request error:

Exception : System.Net.Http.HttpRequestException: 400 (Bad Request)
  at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode () [0x0002a] in <996a681f30a44cd685a4da54e11956e2>:0 

=> Would you have any explanation? How could I fix this?

Answers

  • BillyLiuBillyLiu Member, Xamarin Team Xamurai

    Hi @Pierre-ChristopheDus

    400 - Bad Request error

    400 error usually caused by the wrong format of the parameter.
    You could set the encoding and mediatype in StringContent(). Please try to use something like:

    new StringContent(JsonConvert.SerializeObject(YourParams), Encoding.UTF8, "application/json");
    
  • Pierre-ChristopheDusPierre-ChristopheDus FRUniversity ✭✭✭

    Hi @BillyLiu,

    You're right, the problem came from a misnamed parameter.

    I had to use Fiddler and see results to diagnose the error.

Sign In or Register to comment.