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();
}
}
}