C# HTTP GETPOST单线程请求、Json反序列化解析对接数据

C# HTTP GETPOST单线程请求、Json反序列化解析对接数据,第1张

写着玩的个人笔记

GET请求写法
	using Newtonsoft.Json;
	using Newtonsoft.Json.Linq;
	using System.Net;
	using System.IO;
	using System.Text;
	using System.Threading;
   
    //线程开启
    public bool OnMeth_GetData(int arg)
	{
		Thread th = new Thread(new ThreadStart(OnUpdataData));
		th.Start();		
		changed = true;
		return true;
	}
    public void OnUpdataData()
	{
			string data = GetHtml(URL);
			requestdata = data;
			Model1.Rootobject rb = JsonConvert.DeserializeObject<Model1.Rootobject>(data);
			//赋值
			out_sixiangshuju = rb.data.gaojinghuizong;
    }
    //GET请求
    string GetHtml(string url)
	{
		string URL = url;		
		try
		{
			HttpWebRequest request = (HttpWebRequest) WebRequest.Create(URL); 
			request.Method = "GET"; 
			request.ContentType = "application/json";
			request.Headers.Set("Authorization", "Basic");
			request.Headers.Set("Tenant-Id","415488");
			request.Timeout = 2000;
			HttpWebResponse response = (HttpWebResponse) request.GetResponse(); 
			Stream myResponseStream = response.GetResponseStream(); 
			StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); 
			string retString = myStreamReader.ReadToEnd(); 
			myStreamReader.Close(); 
			myResponseStream.Close(); 			
			return retString;
		}
		catch (WebException ex)
		{
			throw ex;
		}
	}
	
//实例类
namespace Model1{
	public class Rootobject
	{
		public int code { get; set; }
		public bool success { get; set; }
		public Data data { get; set; }
		public string msg { get; set; }
	}

	public class Data
	{
		public string[] gaojinghuizong { get; set; }
	}
}
POST请求写法
string PostHtml(string url)
	{
		string URL = url;
		try
		{
			HttpWebRequest req = (HttpWebRequest) WebRequest.Create(URL);
			req.Method = "POST";
			req.ContentType = "application/json";
			//req.Headers.Set("Authorization", "86y.org");
			#region 添加Post 参数		
			using (var streamWriter = new StreamWriter(req.GetRequestStream()))
			{
				string json = "{\"year\":\"1\",\"type\":\"1\"}";
				streamWriter.Write(json);
				streamWriter.Flush();
				streamWriter.Close();
			}
			#endregion
			HttpWebResponse resp = (HttpWebResponse) req.GetResponse();
			Stream stream = resp.GetResponseStream();
			string retString;
			//获取响应内容
			using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
			{
				retString = reader.ReadToEnd();
			}
			String2 = retString;
			return retString;
		}catch(Exception ex){bug = ex.Message;}
		return null;
	}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/732469.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-27
下一篇 2022-04-27

发表评论

登录后才能评论

评论列表(0条)

保存