后台访问接口
一、通过转接口获取数据
ContentType :application/x-www-form-urlencoded:输入值为字符串格式
ContentType:application/json:输入值为json格式
第1种:输入字典类型转json类型:
字典:Dictionary<string, object> parameters =new Dictionary<string, object>(); parameters.add(“key”,”value”); string mm = GetPage("http://21.254.198.70:803/api/healthLogin", parameters); /// <summary> /// 指定Post地址 /// </summary> /// <param name="url">请求后台地址</param> /// <returns></returns> public static string Post(string url, Dictionary<string, object> parameters) { try { string jsonString = JsonConvert.SerializeObject(parameters); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/json"; using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream())) { dataStream.Write(jsonString); dataStream.Close(); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); string encoding = response.ContentEncoding; if (encoding == null || encoding.Length < 1) { encoding = "UTF-8"; //默认编码 } StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding)); var retString = reader.ReadToEnd(); return Regex.Unescape(retString); //处理返回的字符比如unicode转为中文 } catch (Exception ex) { throw ex; } }
第2种:json类型:
string mm = GetPage("http://21.254.198.70:803/api/healthLogin", "{\"phone\":\"" + phone + "\",\"code\":\"" + code + "\"}"); public string GetPage(string posturl, string postData) { Stream outstream = null; Stream instream = null; StreamReader sr = null; HttpWebResponse response = null; HttpWebRequest request = null; Encoding encoding = Encoding.UTF8; byte[] data = encoding.GetBytes(postData); try { request = WebRequest.Create(posturl) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; //request.Headers.Add("Cookie", ""+ cookies + "" );//添加类似于头部token之类的时候需要用这个添加 request.AllowAutoRedirect = true; request.Method = "POST"; request.ContentType = "application/json"; request.ContentLength = data.Length; outstream = request.GetRequestStream(); outstream.Write(data, 0, data.Length); outstream.Close(); response = request.GetResponse() as HttpWebResponse; instream = response.GetResponseStream(); sr = new StreamReader(instream, encoding); string content = sr.ReadToEnd(); string err = string.Empty; return content; } catch (Exception ex) { string err = ex.Message; return string.Empty; } }
第3种:url传的是https需要ssl证书时
public static string GetPage(string posturl, string postData)
{
Stream outstream = null;
Stream instream = null;
StreamReader sr = null;
HttpWebResponse response = null;
HttpWebRequest request = null;
Encoding encoding = Encoding.UTF8;
byte[] data = encoding.GetBytes(postData);
try
{
//request = WebRequest.Create(posturl) as HttpWebRequest;
//CookieContainer cookieContainer = new CookieContainer();
//request.CookieContainer = cookieContainer;
//request.AllowAutoRedirect = true;
//--------证书部分
if (posturl.Contains("https"))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
request = (HttpWebRequest)WebRequest.CreateDefault(new Uri(posturl));
}
else
{
request = (HttpWebRequest)WebRequest.Create(posturl);
}
//-------------
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
//----浏览器的通用标识
request.KeepAlive = true;
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36";
//---------
outstream = request.GetRequestStream();
outstream.Write(data, 0, data.Length);
outstream.Close();
response = request.GetResponse() as HttpWebResponse;
instream = response.GetResponseStream();
sr = new StreamReader(instream, encoding);
string content = sr.ReadToEnd();
string err = string.Empty;
return content;
}
catch (Exception ex)
{
string err = ex.Message;
return string.Empty;
}
}
public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; }
第4种:直接获取数据(.NET Coke中mvc项目)
[HttpPost] public string data(string url, object vo) { //传入接口连接和对象类型的参数 string request = JsonConvert.SerializeObject(vo);//将对象参数转化为json格式 IDictionary<string, string> keyValuePairs = new Dictionary<string, string>(); keyValuePairs.Add("stbid", "admin2"); keyValuePairs.Add("token", "9e72b676c19b455fadc5e4b484dbc9ba");//定义两个参数,给两个参数赋值 var data = Utils.HttpUtil.GetResponseData(url, request, "POST", "application/json", null, keyValuePairs); return data; }
二、通过api接口获取数据
1、在控制器名称 public class CommonApiController 上面加入两句话 [Route("api/[controller]/[action]")] [ApiController] 2、 [HttpGet] public ResultMsg<object> GetRequestResult(string apiCode) { BaseRequestV2 request = new BaseRequestV2(); request.ApiCode = apiCode; string strKey = "5cf74f9c2840f2815370f862c42b37d0"; string timeStamp = DateTimeOffset.Now.ToUnixTimeSeconds().ToString();//时间戳 byte[] b = Encoding.Default.GetBytes(strKey + timeStamp);//转化为默认的编码, byte[]字节 b = new MD5CryptoServiceProvider().ComputeHash(b);//MD5加密 string signature = BitConverter.ToString(b).ToLower().Replace("-", ""); request.Data = "signature=" + signature + "×tamp=" + timeStamp; DefaultClient._context = Request.HttpContext; var mydata = DefaultClient.Execute<ResultMsg<object>>(request);//ajax封装在DefaultClient类的Execute方法下
#region 转换处理,通过FilterResult方法获取参数不同分出的数据不同
if (mydata != null && mydata.data != null&&(request.ApiCode.Contains("getUser") || request.ApiCode.Contains("getCulture")))
{
mydata.data = this.FilterResult(request.ApiCode, mydata.data);
}
#endregion
return mydata;
}
public class DefaultClient
{
public static HttpContext _context;
static string serverUrl = Utils.ConfigUtil.GetSection("serverUrl")?.Value;
static string proxyAddr = Utils.ConfigUtil.GetSection("ProxyAddress")?.Value;
public static T Execute<T>(BaseRequestV2 request) where T : BaseResultMsg { string postdata=string.Empty; string posturl; if (request.ApiCode.Contains("http")) { posturl = request.ApiCode; } else { postdata = request.Data; request.ContextType = "application/x-www-form-urlencoded"; posturl = serverUrl + request.ApiCode; } { string result = Utils.HttpUtil.GetResponseDataByAuthorization(posturl, postdata, "", "POST", request.ContextType, proxyAddr); return JsonConvert.DeserializeObject<T>(result); } }
}
/// <summary> /// 结果过滤 /// </summary> /// <param name="apiCode"></param> /// <param name="data"></param> /// <returns></returns> private object FilterResult(string apiCode, object data) { CommonBll commonBll = new CommonBll(); string[] strApi = apiCode.Split("&"); try { switch (strApi[1]) { case "op=getCulture": List<GetCulture> culture = Newtonsoft.Json.JsonConvert.DeserializeObject<List<GetCulture>>(Newtonsoft.Json.JsonConvert.SerializeObject(data)); for (int i = 0; i < culture.Count; i++) { if (culture[i].headimgurl != null) { culture[i].headimgurl = commonBll.DownLoadImg(culture[i].headimgurl); } if (culture[i].picall != null && culture[i].picall.Count > 0) { for (int j = 0; j < culture[i].picall.Count; j++) { culture[i].picall[j] = commonBll.DownLoadImg(culture[i].picall[j]); } } } return culture; case "op=getUser": GetUser user= Newtonsoft.Json.JsonConvert.DeserializeObject<GetUser>(Newtonsoft.Json.JsonConvert.SerializeObject(data)); if(user.qrcode!=null) { user.qrcode= commonBll.DownLoadqrcode(user.qrcode); } return user; } } catch (Exception ex) { return data; } return data; }
二、普通接口
public class PartyController : ApiController
{
protected WebAPIDALDataContext db = DbHelper.GetDataContext();//有一个webdal项目linq to sql类,获取数据库的链接 #region 党员详情 /// <summary> /// 党员详情 /// </summary> /// <param name="deptId">党组织</param> /// <param name="PageIndex">页码</param> /// <param name="PageSize">条数</param> /// <returns></returns> [HttpGet] public HttpResponseMessage protdetails(int deptId, int PageIndex, int PageSize) { ResultMsgPage resultMsg = new ResultMsgPage();//自己定义的返回值类 if (db != null) { var dict = db.SysDictionary.Where(w => true); var dep = db.SysDepartment.Where(w => true); var query = (from a in db.PartyMember where a.isDeleted == 0 select new { a.guid, a.name, a.birthDay, deptname = dep.Where(w => w.Id == a.deptId).FirstOrDefault().Name, a.phoneUrl, a.motto, a.comment, a.deptId, a.sort }); if (!string.IsNullOrEmpty(deptId.ToString())) { query = query.Where(w => w.deptId == deptId); } if (query != null && query.Count() > 0) { resultMsg.StatusCode = 200; resultMsg.Info = "Success"; resultMsg.PageIndex = PageIndex; resultMsg.PageSize = PageSize; resultMsg.Pagenumber = query.Count(); resultMsg.Data = query.OrderBy(a => a.sort).Skip((PageIndex - 1) * PageSize).Take(PageSize).ToList(); } else { resultMsg.StatusCode = 500; resultMsg.Info = "Faild"; resultMsg.Data = "Error"; } } else { resultMsg.StatusCode = 500; resultMsg.Info = "Faild"; resultMsg.Data = "db为null"; } return HttpResponseExtension.toJson(JsonConvert.SerializeObject(resultMsg)); } #endregion }
FromBody和FromForm的区别
1,FromBody:在Action方法传入参数后添加[frombody]属性,参数将以一个整体的josn对象的形式传递。 -----简单的说就是从前端data中获取参数,参数以json格式传递过来,平常使用最多;
2,FromForm:在Action方法传入参数后添加[FromForm]属性,参数将以表单【key:value对Array组】的形式提交。-----简单的说,参数以数组的形式传递,传送文件,图片时使用!
3.当两个都不写时,默认从url中获取参数
例子:
[HttpPost]
public HttpResponseMessage protdetails([ FromBody]fractionVo fraction){}
在c#中发送http请求的方式:
1、GET形式
var httpClient = new HttpClient();
var url = "http://localhost:9000/index.html";
var response = await httpClient.GetAsync(url);
var response = JsonConvert.DeserializeObject<List<ChuangWeiZXXDto>>(responseString);
返回数据转换成对象形式/
2、POST形式
var uri = API.His.GetBiaoQianHSZList(_chaungweipaiHSZ);
var content = new StringContent(JsonConvert.SerializeObject(biaoqianDTO), System.Text.Encoding.UTF8, "application/json");
content.Headers.Add("token", token);//添加头部token
var response = await _httpClient.PostAsync(uri, content);
var resultString = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<BiaoQianVo>(resultString);