簡體   English   中英

如何使用 HTTPclient content type = application/x-www-form-urlencoded POST

[英]How to POST using HTTPclient content type = application/x-www-form-urlencoded

我目前正在開發一個 wp8.1 應用程序 C#,通過從 textbox.texts 創建一個 json 對象 (bm),我設法在 json 中對我的 api 執行 POST 方法。 下面是我的代碼。 我如何采用相同的 textbox.text 並將它們作為content type = 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;
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);

要么

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);
 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 token = response.Content.ReadAsStringAsync().Result;
}
               
//Get response as expected

對我來說最好的解決方案是:

// 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))){}

發布此內容類型且不使用字典的另一種變體是:

StringContent postData = new StringContent(JSON_CONTENT, Encoding.UTF8, "application/x-www-form-urlencoded");
using (HttpResponseMessage result = httpClient.PostAsync(url, postData).Result)
{
    string resultJson = result.Content.ReadAsStringAsync().Result;
}

您可以像這樣設置值並將它們發送到PostAsync方法:

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

我正在使用具有[FromBody]屬性的 .Net Core 2.1 API,我必須使用以下解決方案才能成功發布到它:

_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"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM