【问题标题】:How to POST using HTTPclient content type = application/x-www-form-urlencoded如何使用 HTTPclient 内容类型进行 POST = application/x-www-form-urlencoded
【发布时间】:2017-08-26 18:18:03
【问题描述】:

我目前正在开发一个 wp8.1 应用程序 C#,通过从 textbox.texts 创建一个 json 对象 (bm),我设法在我的 api 中执行 json 中的 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;

【问题讨论】:

    标签: c# windows-phone-8.1


    【解决方案1】:
     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(params)).Result;
        var token = response.Content.ReadAsStringAsync().Result;
    }
                   
    //Get response as expected
    

    【讨论】:

    • params 是如何变成dict ? 的?
    【解决方案2】:

    发布此内容类型且不使用字典的另一种变体是:

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

    【讨论】:

      【解决方案3】:

      对我来说最好的解决方案是:

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

      【讨论】:

        【解决方案4】:

        我使用的是带有[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"));
        

        【讨论】:

        • 关于x-www-form-urlencoded的问题是json
        【解决方案5】:
        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);
        

        【讨论】:

        • 您也可以将字典传递给FormUrlEncodedContent 的构造函数,因为字典是KeyValuePairs 的IEnumerable
        • 在Task方法中使用await ?
        • @Kiquenet 是的,在“异步任务”方法中
        猜你喜欢
        • 2019-05-01
        • 2020-04-21
        • 2018-04-04
        • 1970-01-01
        • 2021-02-03
        • 2015-04-02
        • 1970-01-01
        • 2019-11-13
        相关资源
        最近更新 更多