Come eseguire il POST utilizzando HTTPclient content type = application / x-www-form-urlencoded


105

Attualmente sto sviluppando un'applicazione wp8.1 C #, sono riuscito a eseguire un metodo POST in json sulla mia api creando un oggetto json (bm) da textbox.texts. ecco il mio codice qui sotto. Come prendo lo stesso textbox.text e inseriscili come tipo di contenuto = application / x-www-form-urlencoded. qual è il codice per quello?

            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;

Risposte:


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
Puoi anche passare un dizionario al costruttore di FormUrlEncodedContent, poiché Dictionary è un IEnumerabledi KeyValuePairs.
Sam Magura

Usando il metodo await in Task?
Kiquenet

1
@Kiquenet sì, nel metodo "
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 soluzione migliore per me è:

// 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

Puoi impostare i valori in questo modo e inviarli al PostAsyncmetodo:

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
L'API in questione non consenteapplication/json
Fawad Raza

-1

Stavo utilizzando un'API .Net Core 2.1 con l' [FromBody]attributo e ho dovuto utilizzare la seguente soluzione per pubblicare con successo:

_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"));
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.