C#winform调用接口实例
Posted 擅长死循环
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 = this.txtsMasterdataSourceBindingRegionDesc.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
// + 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("http://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、.net 调用webaip
string url = ConfigurationManager.AppSettings["WordD"].ToString();
int i = 0;
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-urlencoded")).Result;
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);
以上是关于C#winform调用接口实例的主要内容,如果未能解决你的问题,请参考以下文章
C#winform中为啥一个窗体的对象可以调用在另一个窗体中创建的一个类未实例化下