<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Post 归档 - 初晴神社</title>
	<atom:link href="https://vki.cc/tag/post/feed/" rel="self" type="application/rss+xml" />
	<link>https://vki.cc/tag/post/</link>
	<description>白露的博客</description>
	<lastBuildDate>Tue, 08 Jan 2019 04:44:54 +0000</lastBuildDate>
	<language>zh-Hans</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1</generator>

<image>
	<url>https://cdn.vki.cc/wp-content/uploads/2018/03/cropped-icemaplen-1-32x32.png</url>
	<title>Post 归档 - 初晴神社</title>
	<link>https://vki.cc/tag/post/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>使用C#实现POST消息发送和读取</title>
		<link>https://vki.cc/greattruth/language/634/</link>
					<comments>https://vki.cc/greattruth/language/634/#comments</comments>
		
		<dc:creator><![CDATA[白露]]></dc:creator>
		<pubDate>Fri, 21 Dec 2018 07:41:18 +0000</pubDate>
				<category><![CDATA[语言相关]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Post]]></category>
		<category><![CDATA[原创]]></category>
		<category><![CDATA[心得]]></category>
		<guid isPermaLink="false">http://www.icemaplen.com/?p=634</guid>

					<description><![CDATA[<p>之前给一个大佬做有赞应用时候遇到了post收发的问题，其实实现起来很简单的。无奈网上关于这方面的资料很少，特此整理一下，希望帮助有需要的人_(:з」∠)_</p>
<p><a href="https://vki.cc/greattruth/language/634/">使用C#实现POST消息发送和读取</a>最先出现在<a href="https://vki.cc">初晴神社</a>。</p>
]]></description>
										<content:encoded><![CDATA[<p><span style="color: #808080;">啊，好久没写过博客了_(:з」∠)_</span></p>
<blockquote><p><span style="color: #333333;">之前给一个大佬做有赞应用时候遇到了post收发的问题，其实实现起来很简单的。无奈网上关于这方面的资料很少，特此整理一下，希望帮助有需要的人_(:з」∠)_</span></p></blockquote>
<h2 id="%e5%8f%91%e9%80%81">发送</h2>
<p>直接上代码了，关键的地方我加了注释，应该不难理解。</p>
<p>C#提供了相关的API，很方便。这段代码可以直接拿去用_(:з」∠)_</p>
<p>大致步骤就是创建Request-填充信息-发送。</p>
<pre class="pure-highlightjs"><code class="cs">/// &lt;summary&gt;
/// Post提交数据
/// &lt;/summary&gt;
/// &lt;param name="postUrl"&gt;URL&lt;/param&gt;
/// &lt;param name="paramData"&gt;参数&lt;/param&gt;
/// &lt;returns&gt;&lt;/returns&gt;
string PostWebRequest(string postUrl, string paramData)
{
    string ret = string.Empty;
    try
    {
        byte[] byteArray = Encoding.UTF8.GetBytes(paramData);
        HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
        // 提交方法，POST/GET等
        webReq.Method = "POST";
        // ContentType
        webReq.ContentType = "application/x-www-form-urlencoded";
        webReq.ContentLength = byteArray.Length;

        Stream newStream = webReq.GetRequestStream();
        //写入参数
        newStream.Write(byteArray, 0, byteArray.Length);
        newStream.Close();
        HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
        StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
        ret = sr.ReadToEnd();

        sr.Close();
        response.Close();
        newStream.Close();
    }
    catch (Exception ex)
    {
        return ex.Message;
    }
    return ret;
}</code></pre>
<h2 id="%e6%8e%a5%e6%94%b6">接收</h2>
<p>接收消息模块我分了两部分，一是主体，如何调用api进行监听。这部分需要另开一个线程来处理。</p>
<pre class="pure-highlightjs"><code class="cs">/// &lt;summary&gt;
/// 监听post消息，在收到消息后发送响应消息。
/// 建议使用死循环反复监听，且开启一个线程执行该方法。
/// &lt;/summary&gt;
void ListenWebRequest()
{
    // string url= "需要监听的url范围";
    // 示例：(这里有个坑，见下文)
    string url = "http://127.0.0.1:2333";
    try
    {
        HttpListener listener = new HttpListener();
        listener.Prefixes.Add(url);

        // 开始监听端口，接收客户端请求
        listener.Start();

        // 阻塞主函数至接收到一个客户端请求为止
        // 也可以使用listener.BeginGetContext()异步监听
        HttpListenerContext context = listener.GetContext();
        HttpListenerRequest request = context.Request;
        HttpListenerResponse response = context.Response;

        // msg即为body内容
        string msg = GetBodyString(request);

        // 通过QueryString索引获取post参数
        string sample = request.QueryString["sample"];

        // 收到信息后返回数据
        string responseString = "响应数据";
        response.StatusCode = 200;
        // header头信息
        response.Headers.Add("Access-Control-Allow-Origin", "*");
        // contentType 类型
        response.ContentType = "application/json";
        response.ContentEncoding = System.Text.Encoding.UTF8;
        byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
        response.ContentLength64 = buffer.Length;
        Stream output = response.OutputStream;
        output.Write(buffer, 0, buffer.Length);

        output.Close();
        listener.Stop();
        listener.Close();
    }
    catch (Exception ex)
    {
        // TODO
    }
}</code></pre>
<p>第二部分，由于接收到的post消息中body内容是以流格式的，还需要将其转换为string。</p>
<pre class="pure-highlightjs"><code class="cs">/// &lt;summary&gt;
/// 将body内容解析为String。
/// &lt;/summary&gt;
/// &lt;returns&gt;The body string.&lt;/returns&gt;
/// &lt;param name="request"&gt;Request.&lt;/param&gt;
string GetBodyString(HttpListenerRequest request)
{
    string result = null;
    using (System.IO.Stream body = request.InputStream) // here we have data
    {
        using (System.IO.StreamReader reader = new System.IO.StreamReader(body, request.ContentEncoding))
        {
            result = reader.ReadToEnd();
        }
    }

    if (string.IsNullOrEmpty(result))
    {
        // TODO 读取到空消息
    }
    else
    {
        // TODO 成功读取消息
    }

    return result;
}</code></pre>
<h2 id="%e6%8e%a8%e8%8d%90%e4%b8%80%e4%b8%aapost%e6%b5%8b%e8%af%95%e5%b7%a5%e5%85%b7">推荐一个post测试工具</h2>
<p><span style="color: #ff9900;"><strong>Restlet Client &#8211; REST API Testing</strong></span></p>
<p>谷歌浏览器插件：<span style="color: #0000ff;"><a style="color: #0000ff;" href="https://chrome.google.com/webstore/detail/restlet-client-rest-api-t/aejoelaoggembcahagimdiliamlcdmfm?utm_source=chrome-ntp-icon">下载链接（需要翻墙）</a></span></p>
<p><span style="color: #333333;">炒鸡好用！</span></p>
<p><img  fetchpriority="high"  decoding="async"  class="aligncenter wp-image-636 size-full"  src="https://cdn.vki.cc/wp-content/uploads/2018/12/20181221-155002.png"  alt=""  width="1023"  height="551"  srcset="https://cdn.vki.cc/wp-content/uploads/2018/12/20181221-155002.png 1023w, https://cdn.vki.cc/wp-content/uploads/2018/12/20181221-155002-300x162.png 300w, https://cdn.vki.cc/wp-content/uploads/2018/12/20181221-155002-768x414.png 768w, https://cdn.vki.cc/wp-content/uploads/2018/12/20181221-155002-750x404.png 750w"  sizes="(max-width: 1023px) 100vw, 1023px" ></p>
<h2 id="%e7%a2%8e%e7%a2%8e%e5%bf%b5">碎碎念</h2>
<p>就是在接收方法那绑定的url，我当时用的腾讯云的服务器（window系统）测试的。是这样的，</p>
<p>如果url是localhost或127.0.0.1，在服务器本机测试一切正常。但如果从外网向其post数据，会报400或405错误。</p>
<p>如果url是服务器外网IP呢，干脆直接抛异常，好像是无法绑定。</p>
<p>最后尝试了下将url改成内网IP，一切OK。不过我还是不知道是什么原因_(:з」∠)_</p>
<p><a href="https://vki.cc/greattruth/language/634/">使用C#实现POST消息发送和读取</a>最先出现在<a href="https://vki.cc">初晴神社</a>。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://vki.cc/greattruth/language/634/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
	</channel>
</rss>
