一个简单的Httpserver以及获取post提交的参数

以下代码是我从网上找来的,但是一直获取不到post提交的参数,最后经过我的修改,终于可以得到post提交的数据。因为本人在网上找了很久都没有找到相关的资料,特意发出来希望能帮到大家,有什么不足的地方还请大神们指正,小弟不胜感激。

Httpserver代码

 1         public void StartListen()
 2         {
 3             using (HttpListener listerner = new HttpListener())
 4             {
 5                 listerner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;//指定身份验证 Anonymous匿名访问
 6                 listerner.Prefixes.Add("http://localhost:8080/web/");
 7
 8                 // listerner.Prefixes.Add("http://localhost/web/");
 9                 listerner.Start();
10                 Console.WriteLine("WebServer Start Successed.......");
11                 while (true)
12                 {
13                     //等待请求连接
14                     //没有请求则GetContext处于阻塞状态
15                     HttpListenerContext ctx = listerner.GetContext();
16                     ctx.Response.StatusCode = 200;//设置返回给客服端http状态代码
17                     //RequestType=1&Longitude=0.0&Latitude=0.0&RequestSource=xx
18                     string RequestType = "";
19                     string Longitude = "";
20                     string Latitude = "";
21                     string RequestSource = "";
22                     //获取客户端写入的信息
23                     string strRequest = ShowRequestData(ctx.Request);
24                     if (!string.IsNullOrEmpty(strRequest))
25                     {
26                         string[] strR = strRequest.Split(‘&‘);
27                         string[] strP = new string[strR.Length];
28                         for (int i = 0; i < strR.Length; i++)
29                         {
30                             strP[i] = strR[i].Split(‘=‘)[1];
31                         }
32                         RequestType = strP[0];
33                         Longitude = strP[1];
34                         Latitude = strP[2];
35                         RequestSource = strP[3];
36                     }
37                     string strSend = "";
38
39                     if (!string.IsNullOrEmpty(RequestType))
40                     {
41                         if (RequestType == "1" && !string.IsNullOrEmpty(Longitude) && !string.IsNullOrEmpty(Latitude))
42                         {
43                             strSend = GetPointWeather(Longitude, Latitude, RequestSource);
44                         }
45                         if (RequestType == "2")
46                         {
47
48                         }
49                     }
50
51                     //使用Writer输出http响应代码
52                     using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream, Encoding.GetEncoding("gb2312")))
53                     {
54                         writer.WriteLine(strSend);
55                         writer.Close();
56                         ctx.Response.Close();
57                     }
58
59                 }
60                 //listerner.Stop();
61             }
62         }

GetPointWeather函数是我自己定义的,主要是得到返回给客户端的信息。

获取客户端的输入流

 1         public string ShowRequestData(HttpListenerRequest request)
 2         {
 3             if (!request.HasEntityBody)
 4             {
 5                 Console.WriteLine("No client data was sent with the request.");
 6                 return "";
 7             }
 8             System.IO.Stream body = request.InputStream;
 9             System.Text.Encoding encoding = request.ContentEncoding;
10             System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
11             if (request.ContentType != null)
12             {
13                 Console.WriteLine("Client data content type {0}", request.ContentType);
14             }
15             Console.WriteLine("Client data content length {0}", request.ContentLength64);
16
17             Console.WriteLine("Start of client data:");
18             // Convert the data to a string and display it on the console.
19             string s = reader.ReadToEnd();
20             Console.WriteLine(s);
21             Console.WriteLine("End of client data:");
22             body.Close();
23             reader.Close();
24             // If you are finished with the request, it should be closed also.
25             return s;
26         }

post请求代码:

 1         /// <summary>
 2         /// 使用Http请求天气信息
 3         /// </summary>
 4         /// <param name="RequestType">请求类别(1:点预报 2:镇预报)</param>
 5         /// <param name="Longitude">经度(如果是镇预报请求 值为空)</param>
 6         /// <param name="Latitude">纬度(如果是镇预报请求 值为空)</param>
 7         /// <param name="RequestSource">请求来源</param>
 8         public void GetWeatherByHttp(string RequestType, string Longitude, string Latitude, string RequestSource)
 9         {
10             string strURL = "http://localhost:8080/web/";
11             System.Net.HttpWebRequest request;
12             request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
13             //Post请求方式
14             request.Method = "POST";
15             //内容类型
16             request.ContentType = "application/x-www-form-urlencoded";
17             //参数经过URL编码
18             Encoding myEncoding = Encoding.GetEncoding("gb2312");//GetEncoding("gb2312")
19             string paraUrlCoded = HttpUtility.UrlEncode("RequestType", myEncoding);
20             paraUrlCoded += "=" + HttpUtility.UrlEncode(RequestType, myEncoding);
21             paraUrlCoded += "&" + HttpUtility.UrlEncode("Longitude", myEncoding);
22             paraUrlCoded += "=" + HttpUtility.UrlEncode(Longitude, myEncoding);
23             paraUrlCoded += "&" + HttpUtility.UrlEncode("Latitude", myEncoding);
24             paraUrlCoded += "=" + HttpUtility.UrlEncode(Latitude, myEncoding);
25             paraUrlCoded += "&" + HttpUtility.UrlEncode("RequestSource", myEncoding);
26             paraUrlCoded += "=" + HttpUtility.UrlEncode(RequestSource, myEncoding);
27             byte[] payload;
28             //将URL编码后的字符串转化为字节
29             payload = System.Text.Encoding.ASCII.GetBytes(paraUrlCoded);
30             //设置请求的ContentLength
31             request.ContentLength = payload.Length;
32             //获得请求流
33             Stream writer = request.GetRequestStream();
34             //将请求参数写入流
35             writer.Write(payload, 0, payload.Length);
36             //关闭请求流
37             writer.Close();
38             System.Net.HttpWebResponse response;
39             //获得响应流
40             response = (System.Net.HttpWebResponse)request.GetResponse();
41             System.IO.Stream s;
42             s = response.GetResponseStream();
43             string StrDate = "";
44             string strValue = "";
45             StreamReader Reader = new StreamReader(s, Encoding.Default);
46             while ((StrDate = Reader.ReadLine()) != null)
47             {
48                 strValue += StrDate + "\r\n";
49             }
50             // txtInfo.Text = strValue;
51             Reader.Close();
52         }
时间: 2025-01-22 14:35:47

一个简单的Httpserver以及获取post提交的参数的相关文章

phpStudy1——PHP文件获取html提交的参数

示例代码: submit.html 1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <body> 8 <form id="form1" name="form1" method="post" ac

4-1:编写一个简单的留言簿,写入留言提交后显示留言内容。

login.jsp <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+re

简介(1)-概述、一个简单的时间获取客户程序

1.概述 大多数网络应用划分:客户(client)和服务器(server) 一些复杂的网络应用:异步回调通信,即服务器向客户发起请求消息. 协议栈:应用协议.TCP协议.IP协议.以太网协议 局域网(local area network,LAN),广域网(wide area network,WAN). 路由器是广域网的架构设备. 因特网:当今最大的广域网. POSIX:一种被多数厂商采纳的标准. 2.一个简单的时间获取客户程序 1)创建套接字 socket函数 2)指定服务器的IP地址和端口 s

【Linux学习】 写一个简单的Makefile编译源码获取当前系统时间

打算学习一下Linux,这两天先看了一下gcc的简单用法以及makefile的写法,今天是周末,天气闷热超市,早晨突然发现住处的冰箱可以用了,于是先出去吃了点东西,然后去超市买了一坨冰棍,老冰棍居多,5毛钱一根,还有几根1.5的. 嗯 接着说gcc的事 先把源代码贴上来 //gettime.h #ifndef _GET_TIME_H_ #define _GET_TIME_H_ void PrintCurrentTime(); #endif //gettime.c #include <stdio.

http-server:一个简单的零配置命令行的http服务器

首先简介一下http-server: http-server是一个简单的零配置命令行http服务器,他对于生产使用来说足够强大,他是简单和可删节足以用于测试,足够简单易用,而且可用于本地开发 1.首先你要安装node 2.然后可以通过npm来全局安装 sudo cnpm install http-server -g 前几篇博客我也写到过cnpm用法,所以这里我用到了cnpm,安装起来很快 安装成功后 3.开始使用 用cd跳转到你想要的文件夹下面 我使用了test文件夹 cd /path/test

一个简单的零配置命令行HTTP服务器 - http-server (nodeJs)

http-server 是一个简单的零配置命令行HTTP服务器, 基于 nodeJs. 如果你不想重复的写 nodeJs 的 web-server.js, 则可以使用这个. 安装 (全局安装加 -g) : npm install http-server 使用 : 在站点目录下开启命令行输入 node http-server 使用于package.json "scripts": { "start": "http-server -a 0.0.0.0 -p 80

利用HttpClient写的一个简单页面获取

之前就听说过利用网络爬虫来获取页面,感觉还挺有意思的,要是能进行一下偏好搜索岂不是可以满足一下窥探欲. 后来从一本书上看到用HttpClient来爬取页面,虽然也有源码,但是也没说用的HttpClient是哪个版本的,而且HttpClient版本不一样,导致后面很多类也不一样.于是下载了最新的HttpCient版本,并且对着tutorial和网上的文档试着写一个简单的获取页面的例子,最终证明是可行的,但是也遇到了不少问题,而且这个例子也十分简单. import java.io.IOExcepti

一个简单的dos脚本, svn 获取代码 - Tomcat 备份 - Maven 编译 - 停止/启动Tomcat - Tomcat站点 发布

获取最新代码 svn update --username %SVN_USER% --password %SVN_PASSWORD% >> "../%LOG_FILE%" 备份Tomcat 站点 md "%APP_ROOT%\backup\%MVN_PROFILE%-%CUR_DATE%-%myran%" >> "%LOG_FILE%" xcopy "%APP_ROOT%\%MVN_PROFILE%" &

一个简单的获取参数的jqure

今天做项目的时候需要用到上一页面传递过来的参数(只要一个参数),其解决办法就是下面: char latter=location.search.split('=')[1] 以上直接获取到第一个参数的值为字符串型,接下来想怎么用这个参数就看自己了! 网上也有以下的解决办法,未测试!仅供参考! var id; function getid() { var url=location.search; var Request = new Object(); if(url.indexOf("?")!