话不多说,直接上代码:
post上传JSON数据
string url = 接口地址+"setscdl";
Result ysdUpLoadResult = new Result();
WebRequest request = WebRequest.Create(url);
request.Method = "post";
string data = Newtonsoft.Json.JsonConvert.SerializeObject(productionQueue);
//格式化JSON数据
try
{
JsonSerializer serializer = new JsonSerializer();
TextReader tr = new StringReader(data);
JsonTextReader jtr = new JsonTextReader(tr);
object obj = serializer.Deserialize(jtr);
if (obj != null)
{
StringWriter textWriter = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
{
Formatting = Formatting.Indented,
Indentation = 4,//缩进字符数
IndentChar = ' '//缩进字符
};
serializer.Serialize(jsonWriter, obj);
data = textWriter.ToString();
}
}
catch (Exception ex)
{
l.datelog("错误的JSON");
}
byte[] byteData = Encoding.UTF8.GetBytes(data);
request.ContentLength = byteData.Length;
request.ContentType = "application/json";
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
WebResponse response;
try
{
response = request.GetResponse();
}
catch (WebException ex)
{
response = ex.Response;
}
StreamReader reader = new StreamReader(response.GetResponseStream());
string result = reader.ReadToEnd();
ysdUpLoadResult = JsonConvert.DeserializeObject<Result>(result);
if (ysdUpLoadResult.code == "正常")
{
l.datelog("成功!");
}
else
{
l.datelog("失败");
}
get获取JSON数据
string ysdToken = "";
JsonMess jsonMess = new JsonMess();
HttpWebRequest req =
(HttpWebRequest)WebRequest.Create(url);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
try
{
//获取内容
using (StreamReader reader = new StreamReader(stream))
{
Ingredients ingredients = new Ingredients();
ysdToken = reader.ReadToEnd();
jsonMess = JsonConvert.DeserializeObject<JsonMess>(ysdToken);
}
}
希望对大家有帮助!