首页 前端知识 .net通过类组装数据转换为json并且传递给对方接口

.net通过类组装数据转换为json并且传递给对方接口

2024-11-04 10:11:12 前端知识 前端哥 845 907 我要收藏

1、根据传递字段创建一个类

public class User

{

 public string code{ get; set; }

public string name{ get; set; }

public string? email{ get; set; }

public string? address{ get; set; }

}

2、根据对方返回字段创建一个类

public class Result
{
    /// <summary>
    /// 数据接收成功
    /// </summary>
    public string msg { get; set; }
    /// <summary>
    /// 
    /// </summary>
    public string code { get; set; }
}

3、组装数据并且转换为json传递给某个接口

private void TransferToJson()

{

User  user= new User();

user.code="zhangsan";

user.name="张三";

user.email="12334567890@163.com";

user.address="上海市静安区";

//转换为json串

string json = "[" + JsonConvert.SerializeObject(user) + "]";

string url="对方的接口地址";

HttpWebRequest req = GetWebRequest(url, "POST", null);
req.Headers.Add(HttpRequestHeader.AcceptCharset, "utf-8");
req.ContentType = "application/json";

 byte[] postData = Encoding.UTF8.GetBytes(json);
 Stream reqStream = req.GetRequestStream();
 reqStream.Write(postData, 0, postData.Length);
 reqStream.Close();

HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
var code = string.IsNullOrEmpty(rsp.CharacterSet) || "ISO-8859-1".Equals(rsp.CharacterSet, StringComparison.CurrentCultureIgnoreCase) ? "UTF-8" : rsp.CharacterSet;
Encoding encoding = Encoding.GetEncoding(code);
string response = GetResponseAsString(rsp, encoding);

Result rs = JsonConvert.DeserializeObject<Result>(response);
//对方返回的结果
if (rs.code == "200")
{

//记录到日志
    Log(rs.msg + ":" + json);
}
else
{
    throw new System.Exception(rs.msg);
}

}

4、日志函数

private void Log(string LogStr)
{
    //Trace.WriteLine(LogStr);
    //return;
    StreamWriter sw = null;
    try
    {
        LogStr = DateTime.Now.ToLocalTime().ToString() + "\n" + LogStr;
        sw = new StreamWriter("C:\\PLMLoggerData\\DangAnData" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt", true);
        sw.WriteLine(LogStr);
    }
    catch
    {
    }
    finally
    {
        if (sw != null)
        {
            sw.Close();
        }
    }
}

转载请注明出处或者链接地址:https://www.qianduange.cn//article/19964.html
标签
.netcore
评论
发布的文章
大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!