c# - StringContent 与 FormUrlEncodedContent

标签 c# http-post

我有一个 URL,我想以 data="blahblahblah"的形式发布一个带有参数的正文。但是,在这种情况下,我的“blahblahblah”是一个完整的 XML,我将其简化为如下所示:

      <Parent id="1">
         <Child id="1"/>
      </Parent>

我可以使用以下方法使它与 HTTPClient FormUrlEncodedContent 一起正常工作。

        var values = new List<KeyValuePair<string, string>>();
        values.Add(new KeyValuePair<string, string>("data", XMLBody));
        var content = new FormUrlEncodedContent(values);
        HttpResponseMessage sResponse = await sClient.PostAsync(action.URL, content).ConfigureAwait(false);

现在我想让它与 StringContent 一起使用。 基本上将 xml 作为参数值的一部分发送,并且该 xml 包含“=”。下面的代码不起作用,因为我可以发布它但服务器无法识别 xml 数据。我在这里做错了什么吗?

StringContent content = new StringContent(HttpUtility.UrlEncode(action.Body), Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage sResponse = await sClient.PostAsync(action.URL, content ).ConfigureAwait(false);

最佳答案

我找到了,我必须手动输入data=部分。

StringContent content = new StringContent("data="+ HttpUtility.UrlEncode(action.Body), Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage sResponse = await sClient.PostAsync(action.URL, content ).ConfigureAwait(false);

关于c# - StringContent 与 FormUrlEncodedContent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27531419/

相关文章:

c# - 如何测试 AccessViolationException 的处理

silverlight - 将数据添加到 silverlight HTTP POST 异步

mysql - 如何在 golang 中编写一个通用方法以在任何 mysql 表中插入记录

c# - 无法修改 c :\windows directory 中的 .ini 文件

c# - 如何在该类的属性上调用类方法

C# system.io.filenotfoundexception 异常

c# - WPF MVVM Bind Dictionary<String, List<String>> 到数据网格

http - 如何在 F# 中发出 HTTP POST 请求?

node.js - 招摇: is '😱 Could not render this component, see the console' an error message or can it be ignored

java - 为什么除非我们从服务器读取 POST 响应,否则 HTTP POST 不起作用?