Xamarin POST Request headers

1

Hello friends I would like to send a POST from Xamarin , but I am getting this error when I try to send it and I would like to know if I am sending my headers correctly. When I try to send my app it stops and it throws me an error that says

  

System.InvalidOperationException: Content-Type

This is my function

public async void Access_Api(string userName, string pass, string tok_ty, string acc_tok) {

  HttpClient client = new HttpClient();

  client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(tok_ty, acc_tok);
  client.DefaultRequestHeaders.Add("api-version", "1.0");
  client.DefaultRequestHeaders.Add("Content-Type", "application/x-www-form-urlencoded");

  var values = new Dictionary < string,
    string > {
      {
        "usuario",
        "prueba"
      },
      {
        "contraseña",
        "prueba123"
      },
      {
        "idusuario",
        "1"
      },
    };


  var content = new FormUrlEncodedContent(values);

  var response = await client.PostAsync("http://somewhereintheinternet.com:80/some/where",
    content);

  switch (response.StatusCode) {
    case (System.Net.HttpStatusCode.OK):
      res_Label.Text = "good";
      break;

    case (System.Net.HttpStatusCode.BadRequest):
      res_Label.Text = "no good";
      break;

    case (System.Net.HttpStatusCode.Forbidden):
      res_Label.Text = "no good, Forbidden";
      break;

  }


}

    
asked by E.Rawrdríguez.Ophanim 21.02.2018 в 01:44
source

1 answer

1

Detail in the code comment:

public async void Access_Api(string userName, string pass, string tok_ty, string acc_tok) {

  HttpClient client = new HttpClient();

  client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(tok_ty, acc_tok);
  client.DefaultRequestHeaders.Add("api-version", "1.0");

  //La siguiente línea es innecesaria:  
  //client.DefaultRequestHeaders.Add("Content-Type", "application/x-www-form-urlencoded");

  var values = new Dictionary < string,
    string > {
      {
        "usuario",
        "prueba"
      },
      {
        "contraseña",
        "prueba123"
      },
      {
        "idusuario",
        "1"
      },
    };


  var content = new FormUrlEncodedContent(values);

  var response = await client.PostAsync("http://somewhereintheinternet.com:80/some/where",
    content);

  switch (response.StatusCode) {
    case (System.Net.HttpStatusCode.OK):
      res_Label.Text = "good";
      break;

    case (System.Net.HttpStatusCode.BadRequest):
      res_Label.Text = "no good";
      break;

    case (System.Net.HttpStatusCode.Forbidden):
      res_Label.Text = "no good, Forbidden";
      break;

  }


}
    
answered by 21.02.2018 / 17:26
source