码迷,mamicode.com
首页 > Web开发 > 详细

Web Service

时间:2020-03-09 22:29:36      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:函数   null   rect   put   返回值   read   aik   博客   --   

摘自百度:  Web服务器可以解析(handles)HTTP协议。当Web服务器接收到一个HTTP请求(request),会返回一个HTTP响应(response),例如送回一个HTML页面。为了处理一个请求(request),Web服务器可以响应(response)一个静态页面或图片,进行页面跳转(redirect),或者把动态响应(dynamic response)的产生委托(delegate)给一些其它的程序例如CGI脚本,JSP(JavaServer Pages)脚本,servlets,ASP(Active Server Pages)脚本,服务器端(server-side)JavaScript,或者一些其它的服务器端(server-side)技术。无论它们(译者注:脚本)的目的如何,这些服务器端(server-side)的程序通常产生一个HTML的响应(response)来让浏览器可以浏览。

  Web Service技术, 能使得运行在不同机器上的不同应用无须借助附加的、专门的第三方软件或硬件, 就可相互交换数据或集成。依据Web Service规范实施的应用之间, 无论它们所使用的语言、 平台或内部协议是什么, 都可以相互交换数据。

 

由终端程序调用web服务

调用web服务,首先需要一个请求的地址

string serviceUrl = ConfigurationManager.AppSettings["insertTrainMeasure"].ToString().Replace(‘$‘, ‘&‘);

ConfigurationManager.AppSettings[]是读取程序中app.config文件的方法,括号中填入Key,获取相应的value;

如:<add key="TaskStateUrl" value="http://10.2.101.50:7080/PRODUCT-LES/measure/measure/gettaskstate?taskid={0}"/>

有了请求路径,就可以使用system.Net中的帮助类调用web服务了。

       /// <summary>
       /// get请求服务
       /// </summary>
       /// <param name="requestUrl">地址(地址?+参数)</param>
       /// <param name="timeout">超时设置</param>
        /// <returns>HttpWebRequest</returns>
        public static HttpWebRequest GetHttpGetWebRequest(string requestUrl, int timeout)
        {
            try
            {
               
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);  //根据指定的url创建新的WebRequest实例
                request.Method = "GET";  //请求模式是GET,也可以是POET
                request.Timeout = timeout * 1000;   设置HttpWebRequest.GetGetResponseStream()方法超时时间
                request.ReadWriteTimeout = timeout * 1000;  //设置写入或读取流的超时时间
                request.ContentType = "application/x-www-form-urlencoded";  //设置ContentType HTTP标头的值
                //request.Referer = requestUrl;
                request.Referer = System.Web.HttpUtility.UrlEncode(requestUrl);   //设置Referer标头的值
                request.KeepAlive = false;  //获取或设置一个值,指示是否与internet资源建立持续性连接
               
                return request;
            }             
            catch (Exception ex)
            {
                throw ex;
            }
        }

这个方法最后返回一个HttpWebRequsst类型的对象。

这个对象可以调用GetResponse();方法获取一个WebReponse类型的响应对象。

然后既可以通过GetResponseStream()获取用于读取数据的流对象,通过流读取服务返回的内容


public static string ResponseSynStr(HttpWebRequest req)
        {
            string result = string.Empty;
            WebResponse response = req.GetResponse();
            try
            {
                Encoding encoding = Encoding.GetEncoding("UTF-8");
                using (StreamReader streamReader = new StreamReader(response.GetResponseStream(), encoding))
                {
                    result = streamReader.ReadToEnd();
                    streamReader.Dispose();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                response.Close();
            }
            return result;
        }

最后返回的string类型对象,就是服务返回的内容。

-----------------------------------------------------------------------------------

Post方式与Get方式相差不多

/// <summary>
        /// post请求服务
        /// </summary>
        /// <param name="requestUrl">地址</param>
        /// <param name="timeout">超时设置</param>
        /// <param name="requestXML">参数</param>
        /// <param name="encoding">编码格式 例如:utf-8</param>
        /// <returns>HttpWebRequest</returns>
        public static HttpWebRequest GetHttpPostWebRequest(string requestUrl, int timeout, string requestXML,string encoding)
        {
            try
            {
                encoding = encoding == "" ? "utf-8" : encoding;                //设置编码格式
                byte[] bytes = System.Text.Encoding.GetEncoding(encoding).GetBytes(requestXML);  //将需要传递的参数用设置的编码格式转换为byte数组
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);  //与get相同,根据url建立连接对象
                request.Method = "POST";  //请求方法设置为post
                request.Timeout = timeout * 1000;
                request.ReadWriteTimeout = timeout * 1000;
                request.Referer = requestUrl;
                request.ContentType = "application/json";
                request.ContentLength = bytes.Length;  //设置ContentLength HTTP标头
                request.KeepAlive = false;
                using (Stream requestStream = request.GetRequestStream()) //使用request对象,将参数写入流
                {
                    requestStream.Write(bytes, 0, bytes.Length);
                    requestStream.Close();
                }
                return request;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

POST方法返回与Get方法相同的HttpWebRequest,解读相应对象可以用上边Get相同的方法,

也可使用异步方法:

==============================================================

 HttpWebRequest  request.BeginGetResponse(new AsyncCallback(saveWeightCallback), request);

BeginGetResponse()中需要两个参数,第一个是委托AsyncCallback类型的回调函数。第二个参数是object类型。

////回调函数,有个IAsyncResult
(待处理的响应请求。)
类型的参数
private
void saveWeightCallback(IAsyncResult asyc) { try { string strResult = ComHelpClass.ResponseStr(asyc);     //调用解析方法,见下方 Dictionary<string, object> dic = JsonHelpClass.DeserializeStringToDictionary<string, object>(strResult);//将返回值转变成字典类型 if (bool.Parse(dic["success"].ToString())) { System.Windows.Forms.MessageBox.Show("保存成功"); } else { System.Windows.Forms.MessageBox.Show("保存失败"); } } catch (Exception ex) { } }
////解析方法
public static string ResponseStr(IAsyncResult asyc) { string result = string.Empty; HttpWebRequest httpWebRequest = (HttpWebRequest)asyc.AsyncState;   //将回调函数传递进来的方法转换为HttpWebRequest对象 HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.EndGetResponse(asyc);//结束对Internet资源的异步请求。返回一个WebResponse,其中包含Internet资源的响应。 try { Encoding encoding = Encoding.GetEncoding("UTF-8"); using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), encoding)) { result = streamReader.ReadToEnd(); streamReader.Dispose(); } } catch (Exception ex) { throw ex; } finally { httpWebResponse.Close(); } return result; }

 

 

====================================================================================================

代码摘自某大哥的一篇博客,但是找不到了,以后找到了补上

创建一个web服务

使用HttpListener对象

    
/// <summary>
    /// 一个简单的Web Server实现
    /// 主要负责:
    /// 1.循环接收来自客户端(浏览器)的请求
    /// 2.将请求转给对应的处理者(处理者在第三方编写的网站程序中,通过反射去寻找)
    /// Web Server的作用类似一个“泵”
    /// 整个代码不足70行
    /// </summary>
    class Program
    {
        static IZRouter _router;  //路由器
        static IZHandler _handler;  //请求处理者

        //这个可以设置成配置项,这样的话,Web Server就可以灵活与各种网站程序交互
        //注意网站dll文件名、命名空间等均应与website_name相同。如果需要更加灵活,可以增加配置项,分别配置“网站名称”、“网站dll文件名称”、“命名空间(子命名空间)名称”等
        static string website_name = "MyWebsite"; 

        static void Main(string[] args)
        {
            HttpListener httpListener = new HttpListener();
            httpListener.Prefixes.Add("http://+:8081/");
            httpListener.Start();
            httpListener.BeginGetContext(new AsyncCallback(OnGetContext), httpListener);  //开始异步接收request请求
            Console.WriteLine("监听端口:8081...");
            Console.Read();
        }
        static void OnGetContext(IAsyncResult ar)
        {
            HttpListener httpListener = ar.AsyncState as HttpListener;
            HttpListenerContext context = httpListener.EndGetContext(ar);  //接收到的请求context(一个环境封装体)

            httpListener.BeginGetContext(new AsyncCallback(OnGetContext), httpListener);  //开始 第二次 异步接收request请求


            /*-------------------------开始处理请求-----------------------------*/
            HttpListenerRequest request = context.Request;  //接收的request数据
            HttpListenerResponse response = context.Response;  //用来向客户端发送回复

            //以下开始与 开发者编写的Web网站程序交互
            if (_router == null)  //找网站中的路由器
            {
                Assembly assemble = Assembly.LoadFile(Environment.CurrentDirectory + "\\web\\" + website_name + ".dll"); //加载web目录下的网站程序
                Type type = assemble.GetType(website_name+".Router");  //注意网站程序中的路由器必须命名为 ns.Router
                _router = Activator.CreateInstance(type) as IZRouter;  //创建路由器的实例
            }

            _handler = _router.GetHandler(request.Url.AbsolutePath);  //根据路由器,找web网站中对应的处理者
            if (_handler != null)
            {
                _handler.HandleRequest(request, response);   //开始处理请求(代码运行流程进入web网站程序)
            }
        }
    }

 

/// <summary>
    /// 路由接口,根据url找到对应的请求处理者
    /// </summary>
    public interface IZRouter
    {
        IZHandler GetHandler(string url);
    }

    /// <summary>
    /// 请求处理接口,根据传进来的request、response处理请求并返回处理结果
    /// </summary>
    public interface IZHandler
    {
        void HandleRequest(HttpListenerRequest reqeust, HttpListenerResponse response);
    }
/// <summary>
    /// 每个网站程序必备的路由器,命名必须为Router。该路由器将为每个URL找到对应的处理者
    /// </summary>
    public class Router : IZRouter
    {

        #region IZRouter 成员

        public IZHandler GetHandler(string url)
        {
            //根据URL格式  找到对应的处理者
            //此处简单匹配,完全为了举例
            if (url.EndsWith("/news"))
            {
                return new MyNewsHandler();
            }
            else if (url.EndsWith("/users"))
            {
                return new MyUsersHandler();
            }
            else if (url.EndsWith("/"))
            {
                return new MyIndexHandler();
            }
            //...
            return null;
        }

        #endregion
    }

 

 

 

 

 

Web Service

标签:函数   null   rect   put   返回值   read   aik   博客   --   

原文地址:https://www.cnblogs.com/big-lll/p/12452002.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!