素材巴巴 > 程序开发 >

C#发送http请求之后如何获取返回的数据

程序开发 2023-09-13 20:56:41

在实际开发中,我们经常会使用到API,所谓API一般就是一个地址,我们称之为接口。然后我们通过用C#对这地址发送请求,请求后,服务器就会给我们返回数据,一般是XML或者JSON,这里我们讲述的是JSON。

using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Net;
 using System.IO;namespace WindowsFormsApplication1
 {public class HttpUitls{public static string Get(string Url){//System.GC.Collect();HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);request.Proxy = null;request.KeepAlive = false;request.Method = "GET";request.ContentType = "application/json; charset=UTF-8";request.AutomaticDecompression = DecompressionMethods.GZip;HttpWebResponse response = (HttpWebResponse)request.GetResponse();Stream myResponseStream = response.GetResponseStream();StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);string retString = myStreamReader.ReadToEnd();myStreamReader.Close();myResponseStream.Close();if (response != null){response.Close();}if (request != null){request.Abort();}return retString;}public static string Post(string Url, string Data, string Referer){HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);request.Method = "POST";request.Referer = Referer;byte[] bytes = Encoding.UTF8.GetBytes(Data);request.ContentType = "application/x-www-form-urlencoded";request.ContentLength = bytes.Length;Stream myResponseStream = request.GetRequestStream();myResponseStream.Write(bytes, 0, bytes.Length);HttpWebResponse response = (HttpWebResponse)request.GetResponse();StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);string retString = myStreamReader.ReadToEnd();myStreamReader.Close();myResponseStream.Close();if (response != null){response.Close();}if (request != null){request.Abort();}return retString;}}
 }
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;namespace WindowsFormsApplication1
 {public partial class Form1 : Form{public Form1(){InitializeComponent();}private void button1_Click(object sender, EventArgs e){//我们的接口string url = "http://www.kuaidi100.com/query?type=shunfeng&postid=367847964498";//将接口传入,这个HttpUitls的类,有兴趣可以研究下,也可以直接用就可以,不用管如何实现。string getJson = HttpUitls.Get(url);MessageBox.Show(getJson);}}
 }

文章代码来自:C#从http上拿返回JSON数据 - 心所欲 - 博客园 (cnblogs.com)icon-default.png?t=M4ADhttps://www.cnblogs.com/zoujinhua/p/10330037.html


标签:

素材巴巴 Copyright © 2013-2021 http://www.sucaibaba.com/. Some Rights Reserved. 备案号:备案中。