POST 到我本地主机的 5587 端口

POST to my localhost on port 5587

我希望能够编写与计算机上侦听端口 5587 的应用 运行 交互的代码。

static void Main(string[] args)
{
    HttpPost("http://localhost:5587", "/send/?username=testingname&password=testingpw");
}

public static string HttpPost(string URI, string Parameters)
{
    System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
    req.Proxy = WebRequest.DefaultWebProxy;
    //Add these, as we're doing a POST
    req.ContentType = "application/x-www-form-urlencoded";
    req.Method = "POST";
    //We need to count how many bytes we're sending. Params should be name=value&
    byte[] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
    req.ContentLength = bytes.Length;
    System.IO.Stream os = req.GetRequestStream();
    os.Write(bytes, 0, bytes.Length); //Push it out there
    os.Close();
    System.Net.WebResponse resp = req.GetResponse();
    if (resp == null) return null;
    System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
    resp.Close(); 
    return sr.ReadToEnd().Trim();
}

当我阅读应用程序的规格时,它说:

1) POST 请求 应该是:

http://HOST:PORT/send/? username=user& password=pw& to=destination& bcc=bccDestination& subject=messageSubject

2) 还有 POST data 应该是:

message=messageBody

3) 此外,此 POST 请求 returns 队列中消息的 UUID。此 UUID 稍后用于检查队列中消息的状态。

我该如何更改此代码以完成我需要做的三件事,包括获取带有 ID 的响应以便我可以将其保存以备后用?


编辑:

有一个屏幕截图,显示了我需要的输出与我当前输出的输出。

查询字符串参数应该是uri字符串的一部分,并且需要在请求体中设置一条消息

这样称呼它

string uuid = HttpPost("http://localhost:5587/send/?username=user&password=pw&to=destination&bcc=bccDestination&subject=messageSubject", "message=hi there");
Console.WriteLine(uuid);
Console.ReadLine();

将 HttpPost 方法的最后两行更改为

string uuid = sr.ReadToEnd().Trim();
resp.Close(); 
return uuid;

当然,您需要将参数值更改为有效的值

首先,我想说 HttpClientWebRequest.

更高效、更简单

要使此代码与 HttpClient 一起使用,您需要:

1.Add NuGet 包 Microsoft.AspNet.WebApi.Client(工具>NuGet 包管理器>管理解决方案的 NuGet 包)。

2.Create请求和响应类,如:

    public class RequestClass
    {
        public string message { get; set; }
    }

    public class ResponseClass
    {
        public string UUID { get; set; }
    }

现在,执行 POST 请求的方法(使用泛型和 HttpClient):

    using System;
    using System.Net.Http;
    using System.Net.Http.Headers;

    private static T PostData<T, P>(P postData, string uri, string path)
    {
        var ret = default(T);
        try
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(uri);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));

                var response = client.PostAsXmlAsync(path, postData).Result;
                //var response = client.PostAsJsonAsync(path, postData).Result; if your endpoint accepts json content
                ret = response.Content.ReadAsAsync<T>().Result;
            }
        }
        catch (Exception ex)
        {
            //Do something
        }

        return ret;
    }

这个方法的用法很简单:

        var request = new RequestClass {messageBody = "Something"};
        var uri = "http://localhost:5587";
        var path = "/send?username=user&password=pw&to=destination&bcc=bccDestination&subject=messageSubject";
        var result = PostData<ResponseClass, RequestClass>(request, uri, path); //this will be of type ResponseClass which has the UUID property.

不过请记住,您需要知道端点支持什么内容类型(json、xml、...),以便您可以在 PostData() 方法中指定它。