【问题标题】:POST to my localhost on port 5587在端口 5587 上发布到我的本地主机
【发布时间】:2015-07-08 20:00:04
【问题描述】:

我希望能够编写与在我的计算机上运行的应用程序交互的代码,该应用程序正在侦听端口 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/? 用户名=用户& 密码=密码& 到=目的地& 密送=密送目的地& 主题=消息主题

2) 而且 POST data 应该是:

message=messageBody

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

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


编辑:

我需要的输出与我当前输出的输出的屏幕截图。

【问题讨论】:

    标签: c# post get localhost


    【解决方案1】:

    查询字符串参数应该是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;
    

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

    【讨论】:

    • 正确答案 - 我要补充的唯一一件事是他们在阅读之前关闭了请求。在阅读流之前,您不能 resp.Close()。
    • 谢谢你,巴沃。我已按照您的建议修改了代码。现在很明显,我错误地使用了这个函数并且把它全部错误地调用了。另外,感谢您和 Jacob 接听了我在底部的 close() 呼叫。我什至没有在代码中达到这一点,因为我(现在仍然)收到此错误:System.dll 中发生了“System.Net.WebException”类型的未处理异常附加信息:服务器提交了一个协议违反。 Section=ResponseStatusLine 我用谷歌搜索了这个并找到了一些答案,但没有一个有效....
    • 解决方案之一是更新配置文件并执行看起来只是将错误扫到地毯下并在全球范围内吃掉它。我宁愿修复它试图告诉我的任何东西。哦,那个错误发生在 System.Net.WebResponse resp = req.GetResponse();在接近尾声的地方下线。有什么想法吗?
    • 您的服务是否正常工作,您可以使用 fiddler 发送请求以查看其是否准备就绪。
    • 看起来您的应用没有正确响应,响应状态未设置为响应看起来像,您可以调试并查看发回的响应详细信息,或使用提琴手。
    【解决方案2】:

    首先,我想说的是,HttpClientWebRequest 更加高效和简单。

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

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

    2.创建Request和Response类,如:

        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() 方法中指定它。

    【讨论】:

    • 谢谢你!我让它几乎可以工作。我将 var 请求行更改为“message”而不是“messageBody”,但仅此而已。不过,巧合的是,我无法让它与 POST 一起发送消息。我的本地主机 5587 上有一个监听器,所以我可以看到里面有什么,它只是做 POST 和标题信息,但我从来没有在任何地方看到 message= 部分。有什么想法吗?
    • 这是我的数据的屏幕截图,它被这个监听应用程序拾取:i.imgur.com/TvisIsL.png message= 部分不应该在红色箭头所在的位置吗?
    • 你能分享你的监听器端点的代码吗? (例如 /save 方法)
    • 尝试将client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));更改为client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
    • 监听器应用被关闭和第三方。我无法访问其代码。但它确实对 Fiddler 反应良好。
    猜你喜欢
    • 2019-07-30
    • 2017-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-08
    • 2012-06-03
    • 2018-06-07
    • 1970-01-01
    相关资源
    最近更新 更多