C#发送http请求并转换json结果为对象
前言
一般http请求都是由浏览器端发送的,当然C#也可以借助一些类来达到发送请求,这样就可以使用C#来作为前端访问我们java/python后端了
一、Http工具类
示例:在这里我们来使用两种方式访问后端的接口
1.HttpWebRequest
推荐该方式,封装后可返回response数据然后进行逻辑处理
class HttpRequest
{
public static string baseUrl = "http://localhost:8089";
public static String createGet(String url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseUrl + url);
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream getStream = response.GetResponseStream();
StreamReader streamreader = new StreamReader(getStream);
String result = streamreader.ReadToEnd();
streamreader.Close();
return result;
}
public static String createPost(String url, string postDataStr)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseUrl + url);
request.Method = "POST";
request.ContentType = "application/json;charset=UTF-8";
request.ContentLength = postDataStr.Length;
StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);
writer.Write(postDataStr);
writer.Flush();
writer.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8";
}
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
string retString = reader.ReadToEnd();
reader.Close();
return retString;
}
}
在这里我们可以把结果封装为一个Result类
class Result
{
public string message { get; set; }
public Object data { get; set; }
public int status { get; set; }
}
点击第一个测试按钮,然后在米革命空间引入using Newtonsoft.Json就可以使用JsonConvert来转换结果为Result了
private void btnLogin_Click(object sender, EventArgs e)
{
String str = HttpRequest.createPost("/api/user/login?account=xxx&password=xxx", "");
Result result = JsonConvert.DeserializeObject<Result>(str);
Console.WriteLine(result);
if (result.status == 100)
{
MessageBox.Show("SUCCESS", "HI");
}
}
2.HttpClient
在该方式中演示转为对象实体类
public class AngelHttpClient
{
private HttpClient httpClient;
public AngelHttpClient()
{
httpClient = new HttpClient() { BaseAddress = new Uri("http://127.0.0.1:8089") };
httpClient.Timeout = new TimeSpan(0, 0, 0, 3);
}
public SysUserVO userLogin(string account, string password)
{
string url = "/api/user/user_login?account="+account+"&password="+password;
HttpResponseMessage response = new HttpResponseMessage();
try
{
response = httpClient.PostAsync(url, null).Result;
string respStr = response.Content.ReadAsStringAsync().Result;
LogHelper.WriteLog("respStr:" + respStr);
var respData = JsonHelper.DeserializeAnonymousType(respStr, new { data = new SysUserVO(), message = "", status = 101 });
if (respData.status != 100)
{
/*MessageBox.Show("登录失败!" + respData.message);*/
Console.WriteLine("登录失败!" + respData.message);
return null;
}
/*SysUserVO person = JsonHelper.DeserializeJsonToObject<SysUserVO>(respData.data);*/
return respData.data;
}
catch (Exception ex)
{
LogHelper.WriteLog("HTTP request failed." + ex);
return null;
}
}
}
我们先来建SysUser和SysUserVO,VO继承SysUser并添加了个token属性
public class SysUser
{
public int userId { get; set; }
public string userAccount { get; set; }
public string userPasswd { get; set; }
public string userName { get; set; }
public bool deleteFlag { get; set; }
public override string ToString()
{
return "userName: " + userName + ", userAccount:" + userAccount;
}
}
public class SysUserVO : SysUser
{
public string token { get; set; }
public override string ToString()
{
return "userName: " + userName + ", userAccount:" + userAccount + ", token:"+token;
}
}
然后我们就可以去测试了,JsonHelper代码在下面
private void btnSuper_Click(object sender, EventArgs e)
{
AngelHttpClient angelHttpClient = new AngelHttpClient();
SysUserVO s = angelHttpClient.userLogin("xxx", "xxx");
Console.WriteLine(s);
}
二、转换结果
1.JsonHelper
可以使用帮助类然后将response中的data封装为实体类对象
class JsonHelper
{
/// <summary>
/// 将对象序列化为JSON格式
/// </summary>
public static string SerializeObject(object o)
{
string json = JsonConvert.SerializeObject(o);
return json;
}
/// <summary>
/// 解析JSON字符串生成对象实体
/// </summary>
public static T DeserializeJsonToObject<T>(string json) where T : class
{
JsonSerializer serializer = new JsonSerializer();
StringReader sr = new StringReader(json);
object o = serializer.Deserialize(new JsonTextReader(sr), typeof(T));
T t = o as T;
return t;
}
/// <summary>
/// 解析JSON数组生成对象实体集合
/// </summary>
public static List<T> DeserializeJsonToList<T>(string json) where T : class
{
JsonSerializer serializer = new JsonSerializer();
StringReader sr = new StringReader(json);
object o = serializer.Deserialize(new JsonTextReader(sr), typeof(List<T>));
List<T> list = o as List<T>;
return list;
}
/// <summary>
/// 反序列化JSON到给定的匿名对象.
/// </summary>
public static T DeserializeAnonymousType<T>(string json, T anonymousTypeObject)
{
T t = JsonConvert.DeserializeAnonymousType(json, anonymousTypeObject);
return t;
}
}
2.LogHelper
简单的日志输出
class LogHelper
{
public static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("loginfo");
public static readonly log4net.ILog logerror = log4net.LogManager.GetLogger("logerror");
public static void WriteLog(string info)
{
if (loginfo.IsInfoEnabled)
{
loginfo.Info(info);
}
}
public static void WriteLog(string info, Exception ex)
{
if (logerror.IsErrorEnabled)
{
logerror.Error(info, ex);
}
}
}
总结
感谢观看