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

发布于 2024-12-09 02:26:14 字数 795 浏览 0 评论 0原文

我必须与第三方 API 集成。要使用该服务,我必须使用某些参数“POST”到特定网址。

该服务提供的示例代码位于 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 中实现相同的目的。但是,我对如何设置后参数数据有点困惑。我认为上面的 $data 只是一个字典。所以我创建了一个等效的字典。但是,如何使用字典值设置 post 参数?

http://msdn.microsoft.com/en-us/library/debx8sh9.aspx ,他们将字符串序列化为字节数组,然后将 is 设置为 dataStream 中的 post 参数。我如何对字典做同样的事情?

或者我的方法不正确?有更好的方法吗?

I have to integrate with a third party API. To use the service, I have to "POST" to a specific url with certain parameters.

The example code provided by the service is in php and is as follows

$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);

I am trying to use the WebRequest class to achieve the same in .net. However, I am a bit confused about how to set the post parameter data. I figured $data above is nothing but a Dictionary. So I created a equivalent dictionary. However, how do I set the post parameters with the dictionary values?

In http://msdn.microsoft.com/en-us/library/debx8sh9.aspx, they have serialized a string to a byte array and then set is as the post parameter in the dataStream. How do I do the same for a Dictionary?

Or is my approach incorrect? Is there a better way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

烦人精 2024-12-16 02:26:14

一般来说,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

Generally, WebClient.UploadValues is going to be the easiest approach here; see MSDN for a full example. Note, however, that this only covers CURLOPT_POSTFIELDS and CURLOPT_POST. Fail on error is automatic and implicit, and the response is already included as a byte[].

i.e.

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

note POST is implicit here; if you need a different http method, use the overload:

var result = client.UploadValues(url, "PUT", data); // for example
假扮的天使 2024-12-16 02:26:14

如果您使用 url 编码的发布数据,您可以使用 HttpServerUtility.UrlEncode 方法(字符串)

// 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);
}

If you are using url encoded post data you can url encode each key/value pair of your dictionary using 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);
}
帅气称霸 2024-12-16 02:26:14

以防万一您必须使用 HttpWebRequest,下面的代码会将名为 formVarsDictionary 转换为 byte[ ] 名为 toPost

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

https://dotnetfiddle.net/IOzIE6

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

眼眸里的快感 2024-12-16 02:26:14

您可能想要使用

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();

You probably want to use the

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();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文