通过HttpWebRequest分别向服务器发送GET或POST请求

来源:互联网 发布:全知之眼的意义 编辑:程序博客网 时间:2024/05/01 02:34

10. 通过HttpWebRequest分别向服务器发送GET或POST请求

2009-09-17 16:52:45|  分类: 知识代码库 |  标签: |字号 订阅

1.建立一个控制台应用程序:HttpWebRequest_GET_POST_ConApp
2.Program.cs中的代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace HttpWebRequest_GET_POST_ConApp
{
    class Program
    {
        //The server url
        static string g_DnsUrl = "
http://localhost:2165/UserValidHandler.ashx";
        const string VALIDATION_SUCCESS = "0001";

        static void Main(string[] args)
        {
            //Build the URL
            string strUrl = g_DnsUrl + "?userid=admin&passwd=admin";

            //Initaite HttpWebRequest object
            HttpWebRequest
httpWebRequest = (HttpWebRequest)WebRequest.Create(strUrl);

            //Set the method of the request as "GET"
            httpWebRequest.Method = "GET";

            //Send http request and return the HttpWebResponse object
            HttpWebResponse
httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();

            //Get the response stream
            Stream resStream = httpWebResponse.GetResponseStream();
            byte[] byteResponse = new byte[httpWebResponse.ContentLength];
            resStream.Read(byteResponse, 0, (int)httpWebResponse.ContentLength);

            //Get the response content string
            string strResponse = Encoding.UTF8.GetString(byteResponse);

            //Close the stream
            httpWebResponse.Close();
            resStream.Close();

            //Validation successfully
            if (strResponse == VALIDATION_SUCCESS)
            {
                Console.WriteLine("Validation Successful!");
            }
            else
            {
                Console.WriteLine("Validation Failure!");
            }
            Console.ReadKey();
        }
    }
}
析:以上通过HttpWebRequest发送GET请求到服务器端,那么服务器端又是如何接收GET请求发送过来的数据的呢?请看以下代码:
UserValidHandler.ashx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;

namespace FileUploadWebSite
{
    public class UserValidHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext httpContext)
        {
            httpContext.Response.ContentType = "text/plain";
            string strUserID = httpContext.Request.QueryString["userid"];
            string strUserPassword = httpContext.Request.QueryString["passwd"];

            if (ValidUser(strUserID, strUserPassword) == true)
            {
                httpContext.Response.Write("0001");
            }
            else
            {
                httpContext.Response.Write("0002");
            }
        }

        /// <summary>
        /// Validate User at server side
        /// </summary>
        /// <param name="userID">User Identification</param>
        /// <param name="userPasswd">User Password</param>
        /// <returns></returns>

        public bool ValidUser(string strUserID, string strUserPassword)
        {
            if ((strUserID == "admin") && (strUserPassword == "admin"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
总结:以上是通过Request.QueryString[...]方式获得请求的字符串的。除此之外,还可以通过如下方式获得请求字符串
            string strUserID = httpContext.Request.Params["userid"];
            string strUserPassword = httpContext.Request.Params["passwd"];
          ---------------------------------------------------------------------
            string strUserID = httpContext.Request["userid"];
            string strUserPassword = httpContext.Request["passwd"];
          ---------------------------------------------------------------------
            string strUserID = httpContext.Request.QueryString.GetValues(0)[0];
            string strUserPassword = httpContext.Request.QueryString.GetValues(1)[0];


接下来,我们再看看以POST方式发送请求又是怎样的?
1.先看客户端代码Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace HttpWebRequest_GET_POST_ConApp
{
    class Program
    {
        //The server url
        static string g_DnsUrl = "
http://localhost:2165/UserValidHandler.ashx";
        const string VALIDATION_SUCCESS = "0001";

        static void Main(string[] args)
        {
            //Post Method
            string strParam = "userid=admin&passwd=admin";

            byte[] byteArray = Encoding.ASCII.GetBytes(strParam);
            HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(g_DnsUrl);
            httpWebRequest2.Method = "POST";
            httpWebRequest2.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest2.ContentLength = byteArray.Length;

            using (Stream reqStream = httpWebRequest2.GetRequestStream())
            {
                reqStream.Write(byteArray, 0, byteArray.Length);
            }

            //Send http request and return the HttpWebResponse object
            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest2.GetResponse();

            Stream resStream = httpWebResponse.GetResponseStream();
            byte[] byteResponse = new byte[httpWebResponse.ContentLength];
            resStream.Read(byteResponse, 0, (int)httpWebResponse.ContentLength);

            //Get the response content string
            string strResponse = Encoding.UTF8.GetString(byteResponse);

            //Close the stream
            httpWebResponse.Close();
            resStream.Close();

            //Validation successfully
            if (strResponse == VALIDATION_SUCCESS)
            {
                Console.WriteLine("Validation Successfully!");
            }
            else
            {
                Console.WriteLine("Validation Failure.");
            }
            Console.ReadKey();
        }
    }
}
再看看服务器端的代码:
UserValidHandler.ashx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;

namespace FileUploadWebSite
{
    public class UserValidHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext httpContext)
        {
            httpContext.Response.ContentType = "text/plain";

            Stream reqsStream = httpContext.Request.InputStream;
            long lSize = reqsStream.Length;
            byte[] byteArray = httpContext.Request.BinaryRead((int)lSize);

            //strContent stores the date from the client
            string strContent = Encoding.ASCII.GetString(byteArray);

            string[] strArray = strContent.Split('&');
            string strUserID = strArray[0].Split('=')[1];
            string strUserPassword = strArray[1].Split('=')[1];

            if (ValidUser(strUserID, strUserPassword) == true)
            {
                httpContext.Response.Write("0001");
            }
            else
            {
                httpContext.Response.Write("0002");
            }
        }

        /// <summary>
        /// Validate User at server side
        /// </summary>
        /// <param name="userID">User Identification</param>
        /// <param name="userPasswd">User Password</param>
        /// <returns></returns>

        public bool ValidUser(string strUserID, string strUserPassword)
        {
            if ((strUserID == "admin") && (strUserPassword == "admin"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
总结:两种请求方式不一样,服务器端的处理方式也将不一样。

原创粉丝点击