You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

131 lines
4.2 KiB
C#

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using ZJ_BYD.Model.HttpApiParam;
namespace ZJ_BYD.Common
{
public class HttpUtilApi
{
private static string checkSnCodeUrl = "http://47.93.53.88:8280/scada-collected/checkSnCode";
private static string submitWorkStationDataUrl = "http://47.93.53.88:8280/scada-collected/submitWorkStationData";
/// <summary>
/// 条码验证及查询接口
/// </summary>
/// <param name="checkSnCode"></param>
/// <returns></returns>
public static ResponseParam checkSnCode(CheckSnCode checkSnCode)
{
ResponseParam result = null;
try
{
var jsonStr = JsonConvert.SerializeObject(checkSnCode);
var reqStr = Post(checkSnCodeUrl, jsonStr);
result = JsonConvert.DeserializeObject<ResponseParam>(reqStr);
}
catch (Exception ex)
{
result = new ResponseParam()
{
code = 500,
msg = ex.Message
};
}
return result;
}
/// <summary>
/// 一体机工位提交数据
/// </summary>
/// <param name="workData"></param>
/// <returns></returns>
public static ResponseParam submitWorkStationData(WorkData workData)
{
ResponseParam result = null;
try
{
var jsonStr = JsonConvert.SerializeObject(workData);
var respStr = Post(submitWorkStationDataUrl, jsonStr);
result = JsonConvert.DeserializeObject<ResponseParam>(respStr);
}
catch (Exception ex)
{
result = new ResponseParam()
{
code = 500,
msg = ex.Message
};
}
return result;
}
private static string Post(string Url, string jsonParas)
{
string postContent = "";
string strURL = Url;
//创建一个HTTP请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
//Post请求方式
request.Method = "POST";
//内容类型
request.ContentType = "application/json";
request.UserAgent = "app";
//设置参数并进行URL编码
string paraUrlCoded = jsonParas;//System.Web.HttpUtility.UrlEncode(jsonParas);
byte[] payload;
//将Json字符串转化为字节
payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
//设置请求的ContentLength
request.ContentLength = payload.Length;
//发送请求,获得请求流
Stream writer = null;
try
{
writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象
}
catch (Exception)
{
// writer = null;
//Console.Write("连接服务器失败!");
postContent = "连接服务器失败!";
//writer.Close();//关闭请求流
return postContent;//返回Json数据
}
//将请求参数写入流
writer.Write(payload, 0, payload.Length);
writer.Close();//关闭请求流
// String strValue = "";//strValue为http响应所返回的字符流
HttpWebResponse response;
try
{
//获得响应流
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
response = ex.Response as HttpWebResponse;
}
Stream s = response.GetResponseStream();
// Stream postData = Request.InputStream;
StreamReader sRead = new StreamReader(s);
postContent = sRead.ReadToEnd();
sRead.Close();
return postContent;//返回Json数据
}
}
}