Fork me on GitHub

UWP-webRequest

Week 7

Request

  1. 使用 HttpClient 访问网络
  2. 提供城市天气查询(json Phrase)
  3. 提供 IP 地址查询(xml Phrase)

Accomplish

使用 HttpClient 访问网络

下面参考 Microsoft UWP Document 提供了利用 HttpClient 通过 网址 url 进行网络访问的代码模板。我们要做的事就三个:

  1. 给函数提供访问的 url 所需的参数;
  2. 替换将要访问的 url
  3. 完成下面的 http response处理代码

函数的返回值可以自行修改。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
private async Task<string> WeatherApi(/*params*/) {
HttpClient httpClient = new HttpClient();
var headers = httpClient.DefaultRequestHeaders;

// The safe way to add a header value is to use the TryParseAdd method
// and verify the return value is true,
// especially if the header value is coming from user input.
string header = "ie";
if (!headers.UserAgent.TryParseAdd(header)) {
throw new Exception("Invalid header value: " + header);
}

header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
if (!headers.UserAgent.TryParseAdd(header)) {
throw new Exception("Invalid header value: " + header);
}

string uri = "url";
Uri requestUri = new Uri(uri);
//Send the GET request asynchronously and retrieve the response as a string.
HttpResponseMessage httpResponse = new HttpResponseMessage();
string httpResponseBody = "";

try {
//Send the GET request
httpResponse = await httpClient.GetAsync(requestUri);
httpResponse.EnsureSuccessStatusCode();
// Set encoding to 'UTF-8'
Byte[] getByte1 = await httpResponse.Content.ReadAsByteArrayAsync();
Encoding code1 = Encoding.GetEncoding("UTF-8");
string result1 = code1.GetString(getByte1, 0, getByte1.Length);
// Pharse the json data
JsonReader reader = new JsonTextReader(new StringReader(result1));
while (reader.Read()) {
// Do something here with the response data
}
} catch (Exception ex) {
httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
}
return /*string*/;
}

提供城市天气查询(json Phrase)

下面给出有关于 json phrase 的代码。
这里调用的是中国气象局的api,作为一个年迈的网站,它的查询 url 不支持城市中文名,而应使用城市代码。感谢blouc的贡献,我直接将它洗成 xml 来辅助使用了,具体见代码文件内的 weather.xml 文件。
对于 json 数据的解析,使用 newton 库提供的 json 解析库。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/* Accomplish the url */
// Get the city code for the api
string code = "101010100";
XmlDocument cityCode = new XmlDocument();
cityCode.LoadXml(System.IO.File.ReadAllText("Weather.xml"));
foreach (IXmlNode node in cityCode.GetElementsByTagName("City")) {
if ((string)node.Attributes[0].NodeValue == city) {
code = (string)node.Attributes[2].NodeValue;
}
}
string uri = "http://www.weather.com.cn/data/sk/" + code + ".html";

/* Json Phrase Code for httpResponse data */

//Send the GET request
httpResponse = await httpClient.GetAsync(requestUri);
httpResponse.EnsureSuccessStatusCode();
// Set encoding to 'UTF-8'
Byte[] getByte1 = await httpResponse.Content.ReadAsByteArrayAsync();
Encoding code1 = Encoding.GetEncoding("UTF-8");
string result1 = code1.GetString(getByte1, 0, getByte1.Length);
// Phrase the json data
JsonReader reader = new JsonTextReader(new StringReader(result1));
while (reader.Read()) {
if ((String)reader.Value == "city") {
weather += "城市: ";
reader.Read();
if (reader.Value != null)
weather += reader.Value + "\n";
} else if ((String)reader.Value == "temp") {
weather += "温度: ";
reader.Read();
if (reader.Value != null)
weather += reader.Value + "℃\n";
} else if ((String)reader.Value == "WD") {
weather += "风向: ";
reader.Read();
if (reader.Value != null)
weather += reader.Value + "\n";
} else if ((String)reader.Value == "WS") {
weather += "风速: ";
reader.Read();
if (reader.Value != null)
weather += reader.Value + "\n";
} else if ((String)reader.Value == "SD") {
weather += "相对湿度: ";
reader.Read();
if (reader.Value != null)
weather += reader.Value + "\n";
} else if ((String)reader.Value == "time") {
weather += "时间: ";
reader.Read();
if (reader.Value != null)
weather += reader.Value + "\n";
}
}

提供 IP 地址查询(xml Phrase)

调用网络服务的代码与天气查询的是一致的,只是更换了 url 网址与下面的 httpResponse 处理代码。
这里返回了 xml 数据,我们利用官方提供的

库进行解析。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

```cs
Byte[] getByte = await httpResponse.Content.ReadAsByteArrayAsync();
Encoding code = Encoding.GetEncoding("UTF-8");
string result = code.GetString(getByte, 0, getByte.Length);
// Phrase the xml data
XmlDocument document = new XmlDocument();
document.LoadXml(result);

var province = document.GetElementsByTagName("province");
location += "省份: " + province[0].InnerText + "\n";

var city = document.GetElementsByTagName("city");
location += "城市: " + city[0].InnerText + "\n";

var rectangle = document.GetElementsByTagName("rectangle");
var temp = rectangle[0].InnerText.Split(';');
location += "区域:\n\t" + temp[0] + "\n\t" + temp[1] + "\n";

成品图

Query