.net 4.6环境下
.net4.6支持异步编程
命名空间:
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
创建一个异步方法发送请求:
public static async Task<string> CallWebAPIAsync(string url, string method, string data)
{
using (var client = new HttpClient())
{
HttpResponseMessage response;
if (method.ToUpper() == "GET")
{
// 如果是GET请求
response = await client.GetAsync(url);
}
else if (method.ToUpper() == "POST")
{
// 如果是POST请求
var content = new StringContent(data, Encoding.UTF8, "application/json");
response = await client.PostAsync(url, content);
}
else
{
throw new InvalidOperationException("Unsupported method: " + method);
}
// 确保HTTP请求成功
response.EnsureSuccessStatusCode();
// 读取并返回响应内容
return await response.Content.ReadAsStringAsync();
}
}
调用这个方法:
private async void button1_Click(object sender, EventArgs e)
{
try
{
string data = "{\"id\":\"\",\"properties\":\"\"}";
string url = "";
string method="POST";//GET
string result = await callWebApiAsync(url,method, data);
richTextBox1.Text = result;
}
catch (Exception ex)
{
Console.WriteLine("发生错误: " + ex.Message);
}
}
一定要保证,调用时调用的方法满足异步操作。方法应该标记为async 并返回Task。
如果还有其他需求,比如返回的是一个标准的json格式字符串,那我们可以进行加工,转化为我们需要的json格式数据。
这里需要添加引用“Newtonsoft.Json”
首先找到返回的字符串的json格式,我们一般使用json.cn进行转化,选择“json转c#实体”
将返回结果复制进去即可得到json格式,将格式复制在代码中,例如
public class ResultItem
{
/// <summary>
/// 姓名
/// </summary>
public string name{ get; set; }
}
public class Root
{
/// <summary>
///
/// </summary>
public List<ResultItem> result { get; set; }
/// <summary>
///
/// </summary>
public string success { get; set; }
/// <summary>
///
/// </summary>
public string errorMsg { get; set; }
}
然后进行转化:
try
{
string data = "{\"id\":\"\",\"properties\":{ \name\": \"\"}}";
string url = "";
string method="POST";//GET
string result = await callWebApiAsync(url,method, data);
var v = JsonConvert.DeserializeObject<Root>(result);
v.result.ForEach(x => {
if (x.name.StartsWith("name******")) {
richTextBox1.Text += x.name+"\n";
}
});
}
catch (Exception ex)
{
Console.WriteLine("发生错误: " + ex.Message);
}
.net 4.0环境下
.net4.0没有原生的async、 await
.net不支持HttpClient
通常会使用webclient、httpwebrequest来进行HTTP请求。
命名空间:
using Newtonsoft.Json;
using System.Net;
using System.IO;
http请求:
private static string PostHTTP(string url, string data)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(data);
}
using (var response = (HttpWebResponse)request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
}
调用方法:
private void get()
{
try
{
string url = "";
string data = "{\"id\":\"\",\"properties\":{ \"name\": \"\"}}";
string result = PostHTTP(url, data);
var v = JsonConvert.DeserializeObject<Root>(result);
v.result.ForEach(x => {
if (x.bl_item_item_id.StartsWith("5001*****"))
{
richTextBox1.Text += x.name + "\n";
}
});
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public class ResultItem
{
/// <summary>
/// 姓名
/// </summary>
public string name { get; set; }
}
public class Root
{
/// <summary>
///
/// </summary>
public List<ResultItem> result { get; set; }
/// <summary>
///
/// </summary>
public string success { get; set; }
/// <summary>
///
/// </summary>
public string errorMsg { get; set; }
}