Cómo publicar usando HTTPclient content type = application / x-www-form-urlencoded


105

Actualmente estoy desarrollando una aplicación wp8.1 C #, he logrado realizar un método POST en json en mi api creando un objeto json (bm) desde textbox.texts. aquí está mi código a continuación. ¿Cómo tomo el mismo texto de cuadro de texto y lo envío como un tipo de contenido = application / x-www-form-urlencoded. ¿Cuál es el código para eso?

            Profile bm = new Profile();
            bm.first_name = Names.Text;
            bm.surname = surname.Text;

            string json = JsonConvert.SerializeObject(bm);

            MessageDialog messageDialog = new MessageDialog(json);//Text should not be empty 
            await messageDialog.ShowAsync();

            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");

            byte[] messageBytes = Encoding.UTF8.GetBytes(json);
            var content = new ByteArrayContent(messageBytes);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var response = client.PostAsync("myapiurl", content).Result;

Respuestas:


179
var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("Input1", "TEST2"));
nvc.Add(new KeyValuePair<string, string>("Input2", "TEST2"));
var client = new HttpClient();
var req = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(nvc) };
var res = await client.SendAsync(req);

O

var dict = new Dictionary<string, string>();
dict.Add("Input1", "TEST2");
dict.Add("Input2", "TEST2");
var client = new HttpClient();
var req = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(dict) };
var res = await client.SendAsync(req);

13
También puede pasar un diccionario al constructor de FormUrlEncodedContent, ya que Dictionary es una IEnumerablede KeyValuePairs.
Sam Magura

¿ Estás usando await en el método Task?
Kiquenet

1
@Kiquenet sí, en el método "
Async

18
 var params= new Dictionary<string, string>();
 var url ="Please enter URLhere"; 
 params.Add("key1", "value1");
 params.Add("key2", "value2");

 using (HttpClient client = new HttpClient())
  {
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

HttpResponseMessage response = client.PostAsync(url, new FormUrlEncodedContent(dict)).Result;
              var tokne= response.Content.ReadAsStringAsync().Result;
}

//Get response as expected

5

La mejor solución para mí es:

// Add key/value
var dict = new Dictionary<string, string>();
dict.Add("Content-Type", "application/x-www-form-urlencoded");

// Execute post method
using (var response = httpClient.PostAsync(path, new FormUrlEncodedContent(dict))){}

2

Puede establecer los valores de esta manera y enviarlos al PostAsyncmétodo:

var apiClient = new HttpClient();
var values = new Dictionary<object, object>
{
    {"key1", val1},
    {"key2", "val2"}
};

var content = new StringContent(JsonConvert.SerializeObject(values), Encoding.UTF8, "application/json");
var response = await apiClient.PostAsync("YOUR_API_ADDRESS", content);

1
La API en cuestión no permiteapplication/json
Fawad Raza

-1

Estaba usando una API .Net Core 2.1 con el [FromBody]atributo y tuve que usar la siguiente solución para publicar con éxito en ella:

_apiClient =  new HttpClient();
_apiClient.BaseAddress = new Uri(<YOUR API>);
var MyObject myObject = new MyObject(){
    FirstName = "Me",
    LastName = "Myself"
};

var stringified = JsonConvert.SerializeObject(myObject);
var result = await _apiClient.PostAsync("api/appusers", new StringContent(stringified, Encoding.UTF8, "application/json"));
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.