微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

HTTP POST多部分表单数据

如何解决HTTP POST多部分表单数据

我正在使用Xamarin.Forms开发一个应用程序。我想将发布请求发送到带有表单数据的API。在下面的代码中,它返回成功消息,但是数据没有发布在那里。

public class Post {
    public string ConnectionId { get; set; }
    public string HolderFirstName { get; set; }
    }

public async void SendProof(object sender,EventArgs e) {
    try {
    Uri URL = new Uri(string.Format("http://11.222.333.44:4000/api/v1/Proof/SendProofNameRequest"));
    HttpClient _client = new HttpClient();

    var post = new Post {ConnectionId = "9c12dba2-6cb9-4382-8c96-f1708a7e8816",HolderFirstName = "Carl Dreyer"};
    var content = JsonConvert.SerializeObject(post);
    var response = await _client.PostAsync(URL,new StringContent(content,Encoding.UTF8,"multipart/form-data"));

    if (response.IsSuccessstatusCode) { 
    await DialogService.AlertAsync("Credential Proof Sent Successfully!");}
    }

    catch(Exception error) {
    await DialogService.AlertAsync(error.Message); }
    }

绑定到触发此功能的按钮。

public ICommand SendProofCommand => new Command(() => SendProof(default,default));

解决方法

public async Task SendProof()
        {
            try {
                HttpClient client = new HttpClient(new NativeMessageHandler());
                client.BaseAddress = new Uri("http://11.222.333.44:4000/");
                var postData = new List<KeyValuePair<string,string>>();

                var nvc = new List<KeyValuePair<string,string>>();

                nvc.Add(new KeyValuePair<string,string>("ConnectionId","9c12dba2-6cb9-4382-8c96-f1708a7e8816"));
                nvc.Add(new KeyValuePair<string,string>("HolderFirstName","Bergman"));
                var req = new HttpRequestMessage(HttpMethod.Post,"http://11.222.333.44:4000/" + "api/v1/Proof/SendProofNameRequest") { Content = new FormUrlEncodedContent(nvc) };

                var res = await client.SendAsync(req);

                if (res.IsSuccessStatusCode)
                {
                    await DialogService.AlertAsync("Proof Sent Successfully!");
                }
                else
                {
                    await DialogService.AlertAsync("Unsuccessfull!");
                }
            }
            catch(Exception error) {
            await DialogService.AlertAsync(error.Message);
            }
        }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。