Winform入门(五) WEBAPI请求
2020-08-11 本文已影响0人
熊爸天下_56c7
一. 需要引入:
using System.Net;
using System.IO;
二. 处理get请求
public static string HttpGet(string url, Dictionary<string, string> para)
{
Encoding encoding = Encoding.UTF8;
WebClient webClient = new WebClient();
StringBuilder buffer = new StringBuilder("?");//这是要提交的数据
int i = 0;
foreach (string key in para.Keys)
{
string pk = para[key].Replace('_', '-');
if (i > 0)
{
buffer.AppendFormat("&{0}={1}", key, pk);
}
else
{
buffer.AppendFormat("{0}={1}", key, pk);
}
i++;
}
url = url + buffer.ToString();
Stream stream = webClient.OpenRead(url);
StreamReader sr = new StreamReader(stream);
string str = sr.ReadToEnd();
return str;
}
三. 处理非文件的POST请求
public static string HttpPostNoFile(string url, Dictionary<string, string> para)
{
Encoding encoding = Encoding.UTF8;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);//webrequest请求api地址
request.Accept = "text/html,application/xhtml+xml,*/*";
request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
request.Method = "POST";//get或者post
StringBuilder buffer = new StringBuilder();//这是要提交的数据
int i = 0;
//通过泛型集合转成要提交的参数和数据
foreach (string key in para.Keys)
{
if (i > 0)
{
buffer.AppendFormat("&{0}={1}", key, para[key]);
}
else
{
buffer.AppendFormat("{0}={1}", key, para[key]);
}
i++;
}
byte[] bs = Encoding.UTF8.GetBytes(buffer.ToString());//UTF-8
request.ContentLength = bs.Length;
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
reqStream.Close();
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
{
return reader.ReadToEnd().ToString();
}
}
}
四. 暂停一下先试一试
这里我调用了如下API:
[https://api.apiopen.top/getJoke?page=1&count=2&type=video](https://api.apiopen.top/getJoke?page=1&count=2&type=video)
此API结果如下:
程序中我得到如下结果
Dictionary<string, string> getParm = new Dictionary<string, string> {{"page","1"},{"count","2"},{"type","video"}};
string str1 = HttpGet("https://api.apiopen.top/getJoke", getParm);
label1.Text = str1;
看来是成功了!
五. 如何把JSON字符串转为对象
不同于JS那些亲近JSON的语言. C#转JSON要做的工作更多
- 引入 using Newtonsoft.Json;
- 编写JS字符串到对象的函数
public static T Json2Obj<T>(string s)
{
try
{
return JsonConvert.DeserializeObject<T>(s);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return default;
}
}
- 这里用到了泛型, 所以我们定义一个类, 调用时填充这个泛型
我定义了一个GET1RSP.cs
的类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace autohome
{
public class GET1RSP
{
public virtual string Code { get; set; }
public virtual string Message { get; set; }
public virtual List<AMovie> Result { get; set; }
}
public class AMovie
{
public string sid { get; set; }
public string text { get; set; }
public string type { get; set; }
public string thumbnail { get; set; }
public string video { get; set; }
public string images { get; set; }
public string up { get; set; }
public string down { get; set; }
public string forward { get; set; }
public string comment { get; set; }
public string uid { get; set; }
public string name { get; set; }
public string header { get; set; }
public string top_comments_content { get; set; }
public string top_comments_voiceuri { get; set; }
public string top_comments_uid { get; set; }
public string top_comments_name { get; set; }
public string top_comments_header { get; set; }
public string passtime { get; set; }
}
}
- 当调用时:
GET1RSP test1;
test1 = Json2Obj<GET1RSP>(str1);
六. 对象如何转为JSON字符串??
public static string Obj2Json(object value)
{
return JsonConvert.SerializeObject(value);
}
七. 你可能还会用到: 将对象转为数值
public static decimal ToDecimal(object obj, decimal defaultValue = 0)
{
string s = obj == null ? "" : obj.ToString();
decimal result;
if (!decimal.TryParse(s, out result))
{
result = defaultValue;
}
return result;
}
八 . 下面是一个复杂一点的例子:
这个例子中, 我们回读取一些网络小视频 然后把它列个清单, 同时还尝试把转化的对象转回JSON
主要代码: (创建对象的代码在第五节中)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.IO;
using Newtonsoft.Json;
namespace autohome
{
public partial class Form1 : Form
{
GET1RSP test1;
public static string HttpPostNoFile(string url, Dictionary<string, string> para)
{
Encoding encoding = Encoding.UTF8;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);//webrequest请求api地址
request.Accept = "text/html,application/xhtml+xml,*/*";
request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
request.Method = "POST";//get或者post
StringBuilder buffer = new StringBuilder();//这是要提交的数据
int i = 0;
//通过泛型集合转成要提交的参数和数据
foreach (string key in para.Keys)
{
if (i > 0)
{
buffer.AppendFormat("&{0}={1}", key, para[key]);
}
else
{
buffer.AppendFormat("{0}={1}", key, para[key]);
}
i++;
}
byte[] bs = Encoding.UTF8.GetBytes(buffer.ToString());//UTF-8
request.ContentLength = bs.Length;
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
reqStream.Close();
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
{
return reader.ReadToEnd().ToString();
}
}
}
public static string HttpGet(string url, Dictionary<string, string> para)
{
Encoding encoding = Encoding.UTF8;
WebClient webClient = new WebClient();
StringBuilder buffer = new StringBuilder("?");//这是要提交的数据
int i = 0;
foreach (string key in para.Keys)
{
string pk = para[key].Replace('_', '-');
if (i > 0)
{
buffer.AppendFormat("&{0}={1}", key, pk);
}
else
{
buffer.AppendFormat("{0}={1}", key, pk);
}
i++;
}
url = url + buffer.ToString();
Stream stream = webClient.OpenRead(url);
StreamReader sr = new StreamReader(stream);
string str = sr.ReadToEnd();
return str;
}
public static decimal ToDecimal(object obj, decimal defaultValue = 0)
{
string s = obj == null ? "" : obj.ToString();
decimal result;
if (!decimal.TryParse(s, out result))
{
result = defaultValue;
}
return result;
}
public static string Obj2Json(object value)
{
return JsonConvert.SerializeObject(value);
}
public static T Json2Obj<T>(string s)
{
try
{
return JsonConvert.DeserializeObject<T>(s);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return default;
}
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
GetMovies();
}
private void button2_Click(object sender, EventArgs e)
{
textBox2.Text = Obj2Json(test1);
}
private void GetMovies()
{
Dictionary<string, string> getParm = new Dictionary<string, string> { { "page", numericUpDown1.Value.ToString() }, { "count", numericUpDown2.Value.ToString() }, { "type", "video" } };
string str1 = HttpGet("https://api.apiopen.top/getJoke", getParm);
textBox1.Text = str1;
test1 = Json2Obj<GET1RSP>(str1);
if (test1 != null)
{
Movie1_DES.Text = test1.Result[0].text;
Image pic1 = Image.FromStream(WebRequest.Create(test1.Result[0].thumbnail).GetResponse().GetResponseStream());
Movie1_PIC.Image = pic1;
Movie2_DES.Text = test1.Result[1].text;
Image pic2 = Image.FromStream(WebRequest.Create(test1.Result[1].thumbnail).GetResponse().GetResponseStream());
Movie2_PIC.Image = pic2;
}
imageList1.Images.Clear();
listView1.Items.Clear();
foreach (var item in test1.Result)
{
Image img = Image.FromStream(WebRequest.Create(item.thumbnail).GetResponse().GetResponseStream());
img.Tag = item.text;
imageList1.Images.Add(img);
}
for (int i=0; i<test1.Result.Count; i++)
{
AMovie item = test1.Result[i];
ListViewItem listViewItem1 = new ListViewItem();
listViewItem1.ImageIndex = i;
listViewItem1.SubItems.Add(item.sid);
listViewItem1.SubItems.Add(item.text);
listView1.Items.Add(listViewItem1);
}
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
GetMovies();
}
private void numericUpDown2_ValueChanged(object sender, EventArgs e)
{
GetMovies();
}
}
}