在 .NET 中设置 POST 参数的等效方法是什么?

7
我需要与第三方API集成。为了使用该服务,我必须使用特定参数“POST”到特定的URL。
该服务提供的示例代码是php,如下所示:
$data = array('From' => '0999999', 'To' => '08888888'); 
$curl = curl_init();
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);  <--- Ignore SSL warnings
curl_setopt($curl, CURLOPT_POST, true); 
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

我正在尝试使用WebRequest类在.net中实现相同的功能。然而,我有点困惑如何设置post参数数据。我发现上面的$data只是一个字典。所以我创建了一个等效的字典。但是,我该如何使用字典值设置post参数?
http://msdn.microsoft.com/en-us/library/debx8sh9.aspx中,他们将字符串序列化为字节数组,然后将其设置为dataStream中的post参数。我如何为字典执行相同的操作?
或者我的方法不正确吗?有更好的方法吗?
4个回答

9

通常情况下,WebClient.UploadValues 是最简单的方法; 请参考 MSDN 获取完整示例。但需要注意的是,它仅覆盖了 CURLOPT_POSTFIELDSCURLOPT_POST。在错误发生时会自动失败且隐式,响应已经作为 byte[] 包含在内。

即:

using(var client = new WebClient()) {
    var data = new NameValueCollection();
    data.Add("From", "0999999");
    data.Add("To", "08888888");
    var result = client.UploadValues(url, data);
}

注意这里隐含了使用 POST 方法;如果您需要不同的 HTTP 方法,请使用重载:

var result = client.UploadValues(url, "PUT", data); // for example

是否有类似于CURLOPT_SSL_VERIFYPEER的等效选项,以便我可以忽略任何SSL异常?远程证书是自生成的SSL证书,第三方API开发人员希望其他人忽略任何SSL警告。或者像http://www.ben-morris.com/asp-net-web-services-and-ssl-certificates-establishing-a-trust-relationship中所示的方法是最简单的方法吗?这应该是一个单独的问题吗? - shashi
1
@sassyboy 关于 SSL,请参见 https://dev59.com/wXVD5IYBdhLWcg3wDG_m#865786 - Marc Gravell

4
如果您正在使用URL编码的POST数据,您可以使用HttpServerUtility.UrlEncode Method (String)对字典中的每个键/值对进行URL编码。
// Build postData
StringBuilder post = new StringBuilder();
foreach(item in dictionary) {
  post.AppendFormat("&{0}={1}", item.key, HttpUtility.UrlEncode(item.value));
}
string postData = post.ToString();

// HTTP POST
Uri uri = new Uri(url);
request = (HttpWebRequest) WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
using(Stream writeStream = request.GetRequestStream())
{
  UTF8Encoding encoding = new UTF8Encoding();
  byte[] bytes = encoding.GetBytes(postData);
  writeStream.Write(bytes, 0, bytes.Length);
}

1
第二行有错别字,StringBuilder 拼写错误。 - Timothy C. Quinn

1

如果您必须使用HttpWebRequest,下面的代码将一个名为formVarsDictionary<String,String>转换为一个名为toPostbyte[]

byte[] toPost = System.Text.Encoding.UTF8.GetBytes(
    String.Join("&", formVars.Select(x =>
        HttpUtility.UrlEncode(x.Key) + "=" +
        HttpUtility.UrlEncode(x.Value)));
);

请在 https://dotnetfiddle.net/IOzIE6 上操作工作副本。


0

你可能想使用

http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://url");
request.AllowWriteStreamBuffering = true;
request.Method = "POST";
string post = "From=0999999&To=08888888";
request.ContentLength = post.Length;
request.ContentType = "application/x-www-form-urlencoded";

StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(post);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接