赞
踩
- //设置request参数(新建实体类)
- HttpDataCenterSearchRequest requestData = new HttpDataCenterSearchRequest();
- requestData.clientId = clientId;
- requestData.currentPage = 0;
- requestData.signature = StrResult;
- requestData.sql = sql;
- requestData.timestamp = timestamp;
- //将实体类序列化
- var requestJson = JsonConvert.SerializeObject(requestData);
-
- //调用WebApi
- var res = PostUrl(url, requestJson);
- if (!string.IsNullOrEmpty(res))
- {
- //将返回的res进行反序列化(得到实体类)
- var response = JsonConvert.DeserializeObject<HttpDataCenterSearchResponse>(res);
- if (response != null)
- {
- //赋值
- }
- }
-
- //调用WebApi请求类
- public string PostUrl(string url, string postData)
- {
- try
- {
- HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
- //跳过证书校验(调用https请求时使用)
- req.ServerCertificateValidationCallback = (_s, _x509s, _x509c, _ssl) => { return (true); };
- req.Method = "POST";
- //req.Timeout = 800;//设置请求超时时间,单位为毫秒
- req.ContentType = "application/json";
- byte[] data = Encoding.UTF8.GetBytes(postData);
- req.ContentLength = data.Length;
-
- using (Stream reqStream = req.GetRequestStream())
- {
- reqStream.Write(data, 0, data.Length);
- reqStream.Close();
- }
-
- HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
- Stream stream = resp.GetResponseStream();
-
- //获取响应内容
- string result = "";
- using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
- {
- result = reader.ReadToEnd();
- }
- return result;
- }
- catch (Exception ex)
- {
- MessageBox.Show("WebApi接口调用失败:" + ex.Message);
- return "";
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。