如何使用类库中的 WebRequest 进行发布?

问题描述

我想使用类库调用 API。

这是他们需要我们发送帖子请求的方式

enter image description here

enter image description here

为了实现这一点,我使用此代码

   public class Keey
        {
            public string username { get; set; }
            public string passward { get; set; }
            public string src { get; set; }
            public string dst { get; set; }
            public string msg { get; set; }
            public string dr { get; set; }

        }

public void SendSms(string phoneNo,string SMS)
    {
        Keey account = new Keey
        {

            username = "*****",passward = "*********",src = "test.com",dst = phoneNo,msg = SMS,dr = "1",};



        WebRequest request = WebRequest.Create("http://testserver.com ");
        // Set the Method property of the request to POST.
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = SMS.Length;
        CredentialCache.DefaultNetworkCredentials.UserName = account.username;
        CredentialCache.DefaultNetworkCredentials.Password = account.passward;
        request.Credentials = CredentialCache.DefaultNetworkCredentials;


        WebResponse response = request.GetResponse();

    }

但我不知道在哪里添加这些端口、src、dst、msg 等...请帮帮我

代码在 C# 中

解决方法

这取决于您的 Web-Api 服务。需要什么输入参数。

有几种方法可以执行 POST 请求:

HttpWebRequest(不推荐用于新工作)

using System.Net;
using System.Text;  // For class Encoding
using System.IO;    // For StreamReader


var request = (HttpWebRequest)WebRequest.Create("http://testserver.com/test.aspx");

//your data should place in here
var postData = "thing1=" + Uri.EscapeDataString("hello");
    postData += "&thing2=" + Uri.EscapeDataString("world");
var data = Encoding.ASCII.GetBytes(postData);

request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";

request.ContentLength = data.Length;

using (var stream = request.GetRequestStream())
{
    stream.Write(data,data.Length);
}

var response = (HttpWebResponse)request.GetResponse();

var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

获得这项工作的推荐方式:

using System.Net.Http;



private static readonly HttpClient client = new HttpClient();


POST

var values = new Dictionary<string,string>
{
    { "thing1","hello" },{ "thing2","world" }
};

var content = new FormUrlEncodedContent(values);

var response = await client.PostAsync("http://testserver.com/test.aspx",content);

var responseString = await response.Content.ReadAsStringAsync();