C#winform调⽤接⼝实例
1、C#winform 调⽤webserver 接⼝
try
{
string company = string.Empty;
string str_ ="dd";
company = SalTransaction.DbValSelect(str_, false);
ProductLogist.LogisticServiceClient client = new ProductLogist.LogisticServiceClient();  //引⽤wcf接⼝
ProductLogist.LogisticInfoRequest req = new ProductLogist.LogisticInfoRequest()
{
OrderNo = orderNo,
CompanyID = company,
Address = address,
LinkMan = contact,
Tel = tel,
Dcode = sMasterdataSourceBindingRegionDesc.Text,
LogisticsCompany = logisticsCompany,
Logistics = currEntity.ship_method
};
ProductLogist.LogisticInfoResponse sponse = client.LogisticInfo(req);
if (sponse.LogisticInfoResult.IsOK == "E")
{
if (!sponse.LogisticInfoResult.Message.Contains("不存在该订单"))
{
SalMessage.Error("推送⽣产系统失败:" + sponse.LogisticInfoResult.Message);
return;
}
}
}
catch (Exception ex)
{
SalMessage.Error("推送⽣产系统异常!");
return;
}
2、C#winform 调⽤api接⼝传图multipart/form-data 类型的接⼝
filePath 是打开弹窗后选择的图⽚
url 接⼝地址
-- =====================================================
try
{
string fileName_key_ = "kekename\\" + Path.GetFileName(filePath);
string access_token = "fz434507768345eb7a8e97897";
byte[] fileContentByte = new byte[1024]; // ⽂件内容⼆进制
#region 将⽂件转成⼆进制
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
fileContentByte = new byte[fs.Length]; // ⼆进制⽂件
fs.Read(fileContentByte, 0, Convert.ToInt32(fs.Length));
fs.Close();
#endregion
#region 定义请求体中的内容并转成⼆进制  *********************************************************      重点:拼接参数 ***********************************************                        string boundary = "ceshi";
string Enter = "\r\n";
//string modelIdStr = "--" + boundary + Enter
//        + "Content-Disposition: form-data; name=\"modelId\"" + Enter + Enter
//        + "Content-Disposition: form-data; name=\"modelId\"" + Enter + Enter
//        + modelId + Enter;
string fileContentStr = "--" + boundary + Enter
+ "Content-Type:application/octet-stream" + Enter
+ "Content-Disposition: form-data; name=\"file\"; filename=\"" + filePath + "\"" + Enter + Enter;
string updateTimeStr = Enter + "--" + boundary + Enter
+ "Content-Disposition: form-data; name=\"key\"" + Enter + Enter
+ fileName_key_;
string encryptStr = Enter + "--" + boundary + Enter
+ "Content-Disposition: form-data; name=\"access_token\"" + Enter + Enter
+ access_token + Enter + "--" + boundary + "--";
// var modelIdStrByte = Encoding.UTF8.GetBytes(modelIdStr);//modelId所有字符串⼆进制
var fileContentStrByte = Encoding.UTF8.GetBytes(fileContentStr);//fileContent⼀些名称等信息的⼆进
制(不包含⽂件本⾝)                        var updateTimeStrByte = Encoding.UTF8.GetBytes(updateTimeStr);//updateTime所有字符串⼆进制
var encryptStrByte = Encoding.UTF8.GetBytes(encryptStr);//encrypt所有字符串⼆进制
#endregion *********************************************************      重点:拼接参数 *******************************************************
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "multipart/form-data;boundary=" + boundary;
Stream myRequestStream = request.GetRequestStream();//定义请求流
#region 将各个⼆进制安顺序写⼊请求流 modelIdStr -> (fileContentStr + fileContent) -> uodateTimeStr -> encryptStr
// myRequestStream.Write(modelIdStrByte, 0, modelIdStrByte.Length);
myRequestStream.Write(fileContentStrByte, 0, fileContentStrByte.Length);
myRequestStream.Write(fileContentByte, 0, fileContentByte.Length);
myRequestStream.Write(updateTimeStrByte, 0, updateTimeStrByte.Length);
myRequestStream.Write(encryptStrByte, 0, encryptStrByte.Length);
#endregion
HttpWebResponse response = (HttpWebResponse)request.GetResponse();//发送
Stream myResponseStream = response.GetResponseStream();//获取返回值
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
JObject jo = (JObject)JsonConvert.DeserializeObject(retString);
string Code = jo["code"].ToString();
string desc = jo["desc"].ToString();
string data = jo["data"].ToString();
JObject datajson = (JObject)JsonConvert.DeserializeObject(data);
string file_url_ = datajson["file_url"].ToString();
if (Code == "0")
{
UpdateImgSerialInfo("5", file_url_);
}
else
{
SalMessage.Error("上传图⽚失败,接⼝返回:" + desc);
}
}
catch(Exception ex)
{
SalMessage.Error("上传图⽚出错:" + ex);
}
-- =====================================================
-- =====================================================
3、普通API调⽤ application/json 类型
3.1 调⽤⽅式:
StringBuilder strJSON = new StringBuilder();
strJSON.Append("{ \"TenantID\":\"20191022172020\",");
strJSON.Append("\"TimeStamp\":\"\",");
strJSON.Append(" \"AppID\":\"\"");
strJSON.Append("}");
string key_ = postApi("192.172.10.14:8999/MES/v1/Auth/GetSign", strJSON.ToString());
//组装请求参数
private string BuildQuery(IDictionary<string, string> parameters, string encode)
{
StringBuilder postData = new StringBuilder();
bool hasParam = false;
IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
while (dem.MoveNext())
{
string name = dem.Current.Key;
string value = dem.Current.Value;
// 忽略参数名或参数值为空的参数
if (!string.IsNullOrEmpty(name))
{
if (hasParam)
{
postData.Append("&");
}
postData.Append(name);
postData.Append("=");
if (encode == "gb2312")
{
postData.Append(HttpUtility.UrlEncode(value, Encoding.GetEncoding("gb2312")));
}
else if (encode == "utf8")
{
postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
}
else
{
postData.Append(value);
}
hasParam = true;
}
}
return postData.ToString();
}
private string postApi(string url, string strJSON)
{
HttpWebRequest requestScore = null;
Stream stream = null;
StreamReader reader = null;
HttpWebResponse responseSorce = null;
try
{
{
requestScore = (HttpWebRequest)WebRequest.Create(url);
byte[] data = Encoding.UTF8.GetBytes(strJSON.ToString());
requestScore.Method = "Post";
requestScore.ContentType = "application/json"; // "application/x-www-form-urlencoded";                requestScore.ContentLength = data.Length;
requestScore.KeepAlive = true;
stream = requestScore.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
responseSorce = (HttpWebResponse)requestScore.GetResponse();
reader = new StreamReader(responseSorce.GetResponseStream(), Encoding.UTF8);                string content = reader.ReadToEnd();
return content;
}
catch (Exception ex)
{
return ex.Message;
}
finally
{
requestScore = null;
if (responseSorce != null)
{
responseSorce.Close();
responseSorce = null;
}
if (reader != null)
{
reader.Close();
reader.Dispose();
reader = null;
}
if (stream != null)
{
stream.Close();
stream.Dispose();
stream = null;
}
}
}
4、 调⽤webaip
string url = ConfigurationManager.AppSettings["WordD"].ToString();
int i = 0;
webserver接口开发ResOrderForWork ForWork = null;
StringBuilder strJSON = new StringBuilder();
try
{
strJSON.Append("data={ \"CustomerPhone\":\"" + req.CustomerPhone + "\",");
strJSON.Append("\"OrderNo\":\"" + req.OrderNo + "\",");
strJSON.Append(" \"PayStatus\":\"" + req.PayStatus + "\",");
strJSON.Append("\"OrderLine\":[");
foreach (var r in req.OrderLine)
{
i++;
if (req.OrderLine.Count == i)
{
strJSON.Append("{\"PlateTaskNo\":\"" + r.PlateTaskNo + "\",\"OrderLineNo\":\"" + r.OrderLineNo + "\"}");
}
else
{
strJSON.Append("{\"PlateTaskNo\":\"" + r.PlateTaskNo + "\",\"OrderLineNo\":\"" + r.OrderLineNo + "\"},");
}
}
strJSON.Append("]");
strJSON.Append("}");
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = httpClient.PostAsync(url, new StringContent(strJSON.ToString(), Encoding.UTF8, "application/x-www-form-urlencod                JObject jo = (JObject)JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result);
var Code = jo["code"].ToString();
var desc = jo["desc"].ToString();
var Message = jo["message"].ToString();
ForWork = new ResOrderForWork()
{
Code = Code,
desc = desc,
Message = Message
};
}
catch (Exception e)
{
Common.Log.InsertMessage("[调接⼝异常 : " + e);
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。