写在前面
看了一本书叫做《认知觉醒》上面说60天才会真正养成一个习惯,而21天只是开始,没必要逼自己必须干嘛干嘛,喜欢就做最开心。今天搞点数据,接口。
接口是啥
接口就不解释了,get/post也不解释了,总之项目经验来说,20人以下小公司小项目,三五个后端水平参差不齐的时候,all in post。
写一个接口
算了,找后端要一个。。。
大家做实验的话可以网上随便找点天气预报的免费接口练手,比如下面这个。和风天气开发平台 ~ 高效强大的天气API,天气SDK和天气插件 (qweather.com)
postman 亲测可用以后就开始编码。
分享一个post函数
复制代码
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/// <summary> /// Post数据接口 /// </summary> /// <param name="postUrl">接口地址</param> /// <param name="paramData">提交json数据</param> /// <param name="dataEncode">编码方式(Encoding.UTF8)</param> /// <returns></returns> private static string PostWebRequest(string postUrl, string paramData, Encoding dataEncode) { string reContent = string.Empty; try { //参数转byte byte[] byteArray = dataEncode.GetBytes(paramData); HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl)); webReq.Method = "POST"; webReq.ContentType = "application/json; charset=UTF-8"; webReq.ContentLength = byteArray.Length; using (Stream reqStream = webReq.GetRequestStream()) { //写入参数 reqStream.Write(byteArray, 0, byteArray.Length); } using (HttpWebResponse response = (HttpWebResponse)webReq.GetResponse()) { //在这里对接收到的页面内容进行处理 using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default)) { reContent = sr.ReadToEnd().ToString(); } } } catch (Exception ex) { return ex.Message; } return reContent; }
有些新手调试的时候可能需要注意类型:Content-Type,可以查以下对照表。以下列出几个常用的。
常见的媒体格式类型:
- text/html : HTML格式
- text/plain :纯文本格式
- text/xml : XML格式
- image/gif :gif图片格式
- image/jpeg :jpg图片格式
- image/png:png图片格式
以application开头的媒体格式类型:
- application/xhtml+xml :XHTML格式
- application/xml : XML数据格式
- application/atom+xml :Atom XML聚合格式
- application/json : JSON数据格式
- application/pdf :pdf格式
- application/msword : Word文档格式
- application/octet-stream : 二进制流数据(如常见的文件下载)
- application/x-www-form-urlencoded : <form encType=””>中默认的encType,form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式)
另外一种常见的媒体格式是上传文件之时使用的:
- multipart/form-data : 需要在表单中进行文件上传时,就需要使用该格式
最后记得反序列化不然还是json,有中文的话还会夹杂乱码。
JsonConvert.DeserializeObject<接口类>(返回值);
最后
以上就是哭泣手链最近收集整理的关于MAUI 开发从入门到出门 (5 接口)的全部内容,更多相关MAUI内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复