如何使用HttpClient发布数据?

时间:2013-11-15 16:05:56

标签: c# windows-phone-7 windows-phone-8 windows-phone dotnet-httpclient

我从Nuget获得了this HttpClient。

当我想获取数据时,我这样做:

var response = await httpClient.GetAsync(url);
var data = await response.Content.ReadAsStringAsync();

但问题是我不知道如何发布数据? 我必须发送一个帖子请求并在其中发送这些值:comment="hello world"questionId = 1。这些可以是一个类的属性,我不知道。

更新我不知道如何将这些值添加到HttpContent,因为post方法需要它。 httClient.Post(string, HttpContent);

3 个答案:

答案 0 :(得分:121)

您需要使用:

await client.PostAsync(uri, content);

类似的东西:

var comment = "hello world";
var questionId = 1;

var formContent = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("comment", comment), 
    new KeyValuePair<string, string>("questionId", questionId) 
});

var myHttpClient = new HttpClient();
var response = await myHttpClient.PostAsync(uri.ToString(), formContent);

如果您需要在发布后获得回复,则应使用:

var stringContent = await response.Content.ReadAsStringAsync();

希望它有所帮助;)

答案 1 :(得分:0)

尝试使用此功能:

---
- hosts: localhost
  vars_files:
    - credentials.yml
    - vars.yml
    - se1_hosts.yml

  tasks:
  - name: Manage Log level setting for an ESXi host
    vmware_host_config_manager:
      hostname: 'vcsa.host.se1.somewhere.com'
      username: '{{ vc_username }}'
      password: '{{ vc_pass }}'   
      esxi_hostname:  'hostname'
      # with_items: 
      #   - 'c05n06.esx.se1.csnzoo.com'
      # loop: '{{ hosts }}'
      validate_certs: False
      options:
          'Config.HostAgent.log.level': 'info'
    delegate_to: localhost

答案 2 :(得分:-3)

使用UploadStringAsync方法:

        WebClient webClient = new WebClient();
        webClient.UploadStringCompleted += (s, e) =>
            {
                if (e.Error != null)
                {
                    //handle your error here
                }
                else
                {
                    //post was successful, so do what you need to do here
                }

            };


        webClient.UploadStringAsync(new Uri(yourUri), UriKind.Absolute), "POST", yourParameters);