由于辞职的原因,最近正在忙于找工作。在这段期间收到了一家公司的上机测试题,一共两道题,其中一道题是关于REST API的应用。虽然在面试时,我已经说过,不懂REST,但那面试PM还是给了一道这题让我做。面试的PM还是比较友好,没有限定时间,结果自己不争气,一边查资料一边做,一个多小时过了还是没做出来,所以最后我放弃了,当然面试也就失败了。于是归纳了一下失败的原因,主要还是对REST不了解,把REST当做Web Service的另一种形式,先入为主的理解错误,必然会导致了失败。

回归正传,什么是REST? 在此不详说。我说一下自己的理解吧。简单地说,REST就是一种基本HTTP请求服务从而达到操作资源的技术,其支持多种数据格式,比如xml、Json、Csv等等。Web Service是基本XML并利用SOAP协议实现远程资源访问操作的技术。因此,两者本质是是不同的。也许我的理解不完全正确,欢迎指出错误。

下面来看看这道题,如下:

Userstory:
As a user I want to be able to see maximum, minimum and average predicted temperature for the following 3 days,
based on the city that needs to be entered.
Acceptance criteria:
Windows form application written in C#
One input field to define the city
A combobox to select Fahrenheit or Celcius degrees
Use free web service provided by http://www.worldweatheronline.com
The following key can be used to retrieve data : c6bbde7c9c021451123107
Show 'Retrieving weather data...' in status bar when request of data is submitted. Once data is retrieved
update status accordingly.
Use of linq statements to calculate the minimum, maximum and average temperature.
Main form needs to be responsive at all times
Use of delegates
Retrieval of data and UI logic needs to be seperated in code
Error handling when connection

以下是我写的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Threading; namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Init();
} private void Init()
{
//初始化单位数据
List<object> list = new List<object>();
list.Add(new{key="Celsius", value="C"});
list.Add(new { key = "Fahrenheit", value = "F" });
cbUnit.DataSource = list;
cbUnit.DisplayMember = "key";
cbUnit.ValueMember = "value";
cbUnit.SelectedIndex = 0;
} private void btCalculate_Click(object sender, EventArgs e)
{
try
{
slStatus.Text = "Retrieving weather data.....";
string city = tbCity.Text;
string unit = cbUnit.SelectedValue.ToString();
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("city", city);
dic.Add("unit", unit);
Thread thread = new Thread(new ParameterizedThreadStart(ThreadProcess));
thread.IsBackground = true;
thread.Start(dic);
}
catch (Exception ex)
{
slStatus.Text = "获取数据失败....";
} }
/// <summary>
/// 后台处理线程
/// </summary>
/// <param name="obj"></param>
private void ThreadProcess(object obj)
{
Dictionary<string, string> dic = obj as Dictionary<string, string>;
XDocument xmlDoc = GetData(dic["city"]);
SetData(xmlDoc, dic["unit"]);
slStatus.Text = "";
}
/// <summary>
/// 获取数据
/// </summary>
/// <param name="city"></param>
/// <returns></returns>
private XDocument GetData(string city)
{
XDocument doc;
Uri uri = new Uri(string.Format(@"http://free.worldweatheronline.com/feed/weather.ashx?q={0},china&format=xml&num_of_days=3&key=c6bbde7c9c021451123107",city));
HttpWebRequest request = HttpWebRequest.Create(uri) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string result=reader.ReadToEnd();
StringReader str = new StringReader(result);
doc=XDocument.Load(str);
}
return doc; } /// <summary>
/// 设置数据
/// </summary>
/// <param name="doc"></param>
/// <param name="unit"></param>
private void SetData(XDocument doc,string unit)
{ var query = from p in doc.Root.Elements("weather")
select new {
Date = p.Element("date") == null ? null : p.Element("date").Value,
MaxC = p.Element("tempMaxC") == null ? null : p.Element("tempMaxC").Value,
MinC = p.Element("tempMinC") == null ? null : p.Element("tempMinC").Value,
MaxF = p.Element("tempMaxF") == null ? null : p.Element("tempMaxF").Value,
MinF = p.Element("tempMinF") == null ? null : p.Element("tempMinF").Value
}; if (unit == "C")
{
CrossThreadAccess(tbMaximum, query.Max(p => p.MaxC));
CrossThreadAccess(tbMinimum, query.Min(p => p.MinC)); }
else
{
CrossThreadAccess(tbMaximum, query.Max(p => p.MaxF));
CrossThreadAccess(tbMinimum, query.Min(p => p.MinF)); }
CrossThreadAccess(tbAverage, Convert.ToString((Convert.ToInt32(tbMaximum.Text) + Convert.ToInt32(tbMinimum.Text)) / 2)); } /// <summary>
/// UI线程间访问
/// </summary>
/// <param name="control"></param>
/// <param name="value"></param>
private void CrossThreadAccess(Control control,string value)
{
if (control.InvokeRequired)
{
control.Invoke(new Action<Control, string>(CrossThreadAccess), control, value);
}
else
{
TextBox tb = control as TextBox;
if (tb != null) tb.Text = value; }
} }
}

效果如下:

REST: C#调用REST API (zz)的更多相关文章

  1. Unity在Android和iOS中如何调用Native API

    本文主要是对unity中如何在Android和iOS中调用Native API进行介绍. 首先unity支持在C#中调用C++ dll,这样可以在Android和iOS中提供C++接口在unity中调 ...

  2. C#调用windows API的一些方法

    使用C#调用windows API(从其它地方总结来的,以备查询) C#调用windows API也可以叫做C#如何直接调用非托管代码,通常有2种方法: 1.  直接调用从 DLL 导出的函数. 2. ...

  3. 使用Python调用Flickr API抓取图片数据

    Flickr是雅虎旗下的图片分享网站,上面有全世界网友分享的大量精彩图片,被认为是专业的图片网站.其API也很友好,可以实现多种功能.这里我使用了Python调用其API获得了大量的照片数据.需要注意 ...

  4. WebApi系列~通过HttpClient来调用Web Api接口

    回到目录 HttpClient是一个被封装好的类,主要用于Http的通讯,它在.net,java,oc中都有被实现,当然,我只会.net,所以,只讲.net中的HttpClient去调用Web Api ...

  5. C#调用Windows API函数截图

    界面如下: 下面放了一个PictureBox 首先是声明函数: //这里是调用 Windows API函数来进行截图 //首先导入库文件 [System.Runtime.InteropServices ...

  6. 以短链服务为例,探讨免AppKey、免认证、Ajax跨域调用新浪微博API

    新浪微博的API官方提供了很多种调用方式,支持编程的,归根结底就是两种: 1.基于Oauth协议,使用Open API.(http://open.weibo.com/wiki/%E6%8E%88%E6 ...

  7. 【转】用C#调用Windows API向指定窗口发送

    一.调用Windows API. C#下调用Windows API方法如下: 1.引入命名空间:using System.Runtime.InteropServices; 2.引用需要使用的方法,格式 ...

  8. MSIL 教程(二):数组、分支、循环、使用不安全代码和如何调用Win32 API(转)

    转自:http://www.cnblogs.com/Yahong111/archive/2007/08/16/857574.html 续上文[翻译]MSIL 教程(一) ,本文继续讲解数组.分支.循环 ...

  9. ASP.NET MVC4中调用WEB API的四个方法

    http://tech.it168.com/a2012/0606/1357/000001357231_all.shtml [IT168技术]当今的软件开发中,设计软件的服务并将其通过网络对外发布,让各 ...

随机推荐

  1. android 显示意图

    //显示意图 public void enter(View view) { Intent intent = new Intent();//创建一个空的意图 intent.setClassName(ge ...

  2. Resharper注册机实现以及源代码

    一直用Resharper,每次找注册机也麻烦,就想怎么才能自己能做个注册机,把它原理给搞懂了,不就不用找了.今天早上起来研究了下Resharper注册机,网上找到一位大神之前做Resharper注册机 ...

  3. Effective Java 57 Use exceptions only for exceptional conditions

    Principle Exceptions are, as their name implies, to be used only for exceptional conditions; they sh ...

  4. SSL协议详解

    背景介绍    最近在看<密码学与网络安全>相关的书籍,这篇文章主要详细介绍一下著名的网络安全协议SSL. 在开始SSl介绍之前,先给大家介绍几个密码学的概念和相关的知识.     1.密 ...

  5. mysql基础操作学习笔记(2)----索引

    为什么要创建索引?     在此本人也带着相同的疑问,能够解释的仅仅是:为了减少数据库查询时所需要的速度.如果正常查询和索引查询所需时间相差很多倍时我们自然是需要索引的了. 想要知道结果,只能等我学得 ...

  6. Hadoop Eclipse开发环境搭建

        This document is from my evernote, when I was still at baidu, I have a complete hadoop developme ...

  7. XMLHttpRequest的跨域请求

    缘起 由于浏览器的同源策略,非同源不可请求. 但是,在实践当中,经常会出现需要跨域请求资源的情况,比较典型的例如某个子域名向负责进行用户验证的子域名请求用户信息等应用. 以前要实现跨域访问,可以通过J ...

  8. 虚拟机LVM扩容

    1.先在Vmware上,把虚拟机硬盘做扩展 2.现在打开虚拟机发现系统的磁盘空间已经扩了,但是硬盘分区可用空间没变,还是原来的30G [root@localhost ~]# fdisk -l Disk ...

  9. diff, cmp, patch

    diff 以行为单位比较两个文件之间的差异,经常用来查看同一个文件的新旧版本的差异,通常用在文本文件的比较,可以使用重定向'>'制作补丁文档,通常以.patch结尾 \(diff [-bBi] ...

  10. nyoj 42 一笔画问题 欧拉路径

    题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=42 欧拉回路,欧拉路径水题~ 代码: #include "stdio.h&quo ...