RESTful学习笔记

前两天无意中知道了RESTful这个东西,网上搜了些相关的资料,比如这里

理解RESTful架构

和 这里

视频: RESTful Web Services- NetBeans IDE 6.5

越来越觉得这个东西挺有趣的。

刚接触WEB开发没多久,说的不对的地方,欢迎批评指正,在此先谢谢啦。


本人在完美方面有时会有些偏执狂,REST恰恰在某方面满足了我这方面的胃口:
简单 - 所有的操作都是客户端向服务端请求操作某种资源,很容易学习。

易用 - 一般来说,客户端仅仅通过四个HTTP动词(HEAD, GET, PUT, DELETE)就能完成所有操作。

规范 - 资源名称用名词(非强制、但强烈推荐,所以一般也都如此设计),操作用动词。

安全 - REST推荐使用HTTPS协议,当然HTTP也是木有问题的。

对程序员友好 - 服务端只要做的足够友好,只需要很少的文档,甚至无需文档,当然了这点仰仗设计师的水平了。如访问 https://api.github.com/ 会得到一个所有可用API的网址列表。

跨平台,跨语言 - 只要支持HTTPS、HTTP通讯、读写XML/JSON的编程语言(时至如今,几乎都支持喽),均没问题。

灵活,易于扩展 - 使用XML/JSON传输数据。另外REST有3个成熟度等级,这让我想到了管理课程的CMMI的5个等级。它是一套设计风格,而非架构,是否遵守、如何遵守,全屏个人感觉和意愿,你完全可以根据自己的情况定制。


当然了,我还想到了REST的一些缺点:

新鲜事物(当然对我来说很新鲜了,刚见面几天),支持的站点少,但有github等开源社区和Sun等大厂商推动,这点不是问题,况且还有NetBeans这样利于部署REST的工具。

由于通讯过程的无状态(这点应该是基于HTTP无法避免的缺陷),稳定性有点打折扣,另外会导致每次通讯过程数据的冗余。当然可以在架构设计时,努力减轻这种影响,比如客户端的多次输入合并为一次向服务端的REST请求。

基于HTTPS协议,时效性方面当然要差一些,很难以此为基础开发即时通等产品喽。当然,这也不是REST设计的初衷。


凑个热闹,试着写个用REST的API获取深圳天气情况的小Demo:

这里 World Weather Online 找到了开源的API,但必须先注册一下,然后申请一个“Free-Weather-API Key”,才可以使用。我申请到的Key是:689ab058717194e693b1fc1012fdb857d6874547

(之前尝试用 https://code.google.com/p/weather-china/wiki/API 的API,无需注册即可用,但无奈被伟大的GFW屏蔽,国内用户无法直接访问,所以退而求其次了)


HTML的代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery跨域调用REST天气预报API</title>
<link href="style/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/jquery.js"></script>
</head>

<body>
<div id="main" style="margin-top:10px; width:690px; padding:1px; margin:0 auto; text-align:left;">
	<div>
		<p style="font-family:verdana; font-size:20px; color:green;">
		<span >使用REST获取World Weather Online上深圳的天气</span>
		</p>
	</div>
	
	<div style="margin-top:20px;">
		<span id="weather_text">正在获取深圳的天气情况,请稍等……</span>
	</div>
</div>

<script type="text/javascript">
	$(document).ready(function() {
	  jQuery.getJSON("http://api.worldweatheronline.com/free/v1/weather.ashx?q=Shenzhen&format=JSON&num_of_days=5&key=689ab058717194e693b1fc1012fdb857d6874547&callback=?",
		function(data) {
		  var value="";
		  
		  //解析数组
		  $.each(data.data.weather, function(i, item) {
			value += "日期:"+item.date+"  天气:"+item.weatherDesc[0].value+"  最低温度:"+item.tempMinC+"  最高温度:"+item.tempMaxC+"<br />";
		  });
		  
		  $("#weather_text").html(value);
		});
	});
</script>
</body>
</html>

C#的代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Xml;

namespace RESTTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            XmlDocument doc = new XmlDocument();

            // Create the web request
            HttpWebRequest request = WebRequest.Create("http://api.worldweatheronline.com/free/v1/weather.ashx?q=Shenzhen&format=XML&num_of_days=5&key=689ab058717194e693b1fc1012fdb857d6874547") as HttpWebRequest;

            // Get response
            try
            {
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;

                //判断HTTP响应状态 
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    label1.Text = "资源访问失败!";
                    response.Close();
                    return;
                }
                // Get the response stream
                StreamReader reader = new StreamReader(response.GetResponseStream());
                StringReader str = new StringReader(reader.ReadToEnd());

                doc.Load(str);
            }
            catch (System.Exception ex)
            {
                label1.Text = ex.ToString();
            }
            
            string labelText = "";

            XmlNodeList xmlNodes = doc.SelectNodes("data/weather");
            foreach (XmlNode weatherNode in xmlNodes)
            {
                string date = "";
                string tempMaxC = "";
                string tempMinC = "";
                string weatherDesc = "";

                foreach (XmlNode item in weatherNode.ChildNodes)
                {
                    switch (item.Name)
                    {
                        case "date":
                            date = item.InnerText;
                            break;
                        case "tempMaxC":
                            tempMaxC = item.InnerText;
                            break;
                        case "tempMinC":
                            tempMinC = item.InnerText;
                            break;
                        case "weatherDesc":
                            weatherDesc = item.InnerText;
                            break;
                        default:
                            break;
                    }
                }

                labelText += "日期:" + date + "  天气:" + weatherDesc + "\n";
                labelText += "最低温度:" + tempMinC + "  最高温度:" + tempMaxC + "\n\n";
            }

            label1.Text = labelText;
        }
    }
}


代码打包上传到了CSDN下载,有兴趣的朋友请猛戳这里:http://download.csdn.net/detail/genfeng/7506057

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值