我必须与第三方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参数。我如何为字典做同样的事情?
或者我的方法不正确?有更好的方法吗?
答案 0 :(得分:8)
一般来说,WebClient.UploadValues
将是最简单的方法; see MSDN for a full example。但请注意,这仅涵盖CURLOPT_POSTFIELDS
和CURLOPT_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
答案 1 :(得分:3)
如果您使用网址编码的帖子数据,则可以使用HttpServerUtility.UrlEncode Method (String)
对网址的每个键/值对进行网址编码// 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);
}
答案 2 :(得分:1)
Just in case you have to use HttpWebRequest, the code below converts a Dictionary<String,String>
named formVars
to a byte[]
named toPost
:
byte[] toPost = System.Text.Encoding.UTF8.GetBytes(
String.Join("&", formVars.Select(x =>
HttpUtility.UrlEncode(x.Key) + "=" +
HttpUtility.UrlEncode(x.Value)));
);
Play with a working copy at https://dotnetfiddle.net/IOzIE6
答案 3 :(得分: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();