2017-04-01 30 views
21

Obecnie rozwijam aplikację wp8.1 C#, udało mi się wykonać metodę POST w jsonie do mojego api poprzez utworzenie obiektu json (bm) z textbox.texts. Oto mój kod poniżej. Jak wziąć ten sam textbox.text i POST je jako typ zawartości = application/x-www-form-urlencoded. jaki jest kod?Jak POST przy użyciu typu danych HTTPclient = application/x-www-form-urlencoded

  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; 
+0

mój API jest umożliwienie tylko typ content = application/x-www-form-urlencoded –

Odpowiedz

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

Albo

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); 
+3

Można także przekazać słownika do konstruktora 'FormUrlEncodedContent', ponieważ Słownik to 'IEnumerable' of' KeyValuePair's. –

+0

Korzystanie *** czeka na *** w metodzie Zadanie? – Kiquenet

+0

@Kiquenet tak, w "async Zadanie " metoda –