首页 文章 精选 留言 我的

精选列表

搜索[Web安全],共10000篇文章
优秀的个人博客,低调大师

dotnet core webapi +vue 搭建前后端完全分离web架构(一)

架构 服务端采用 dotnet core webapi 前端采用: Vue + router +elementUI+axios 问题 使用前后端完全分离的架构,首先遇到的问题肯定是跨域访问。前后端可能不在同个server上,即使前后端处在同个server上,由于前后端完全分离, 前后端使用的端口号也可能是不一样的,所以必须解决跨域访问。 具体实现 服务端 服务端使用的dotnetcore +webapi架构,支持cors非常简单,只要引入Microsoft.AspNetCore.Cors 组件,所有问题就迎刃而解了。具体实现如下: 创建 wepapi项目 l Dotnet new webapi l 引入 cors组件 dotnet add package Microsoft.AspNetCore.Cors --version 2.0.1 l 服务端目录结构 l 添加 cors服务 public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } //添加cors 服务 services.AddCors(options => options.AddPolicy("CorsSample",p => p.WithOrigins("http://localhost:5000") .AllowAnyMethod().AllowAnyHeader())); app.UseMvc(); } 设定header original public void ConfigureServices(IServiceCollection services) { services.AddMvc(); //配置Cors app.UseCors("CorsSample"); } l 修改controller的 get 方法 namespace webApiDemo1.Controllers { [Route("api/[controller]")] public class ValuesController : Controller { // GET api/values [HttpGet] [EnableCors("CorsSample")] public IEnumerable<string> Get() { return new string[] { DateTime.Now.ToString() }; } } } l 编译与运行 webapi dotnet run 至此 服务端的所有工作都已完成,测试 客户端 目录结构 搭建webpack 下Vue + router +elementUI 如果不清楚如何搭建 vue+router+elementUI ,请自行度娘。 引入axios 组件 npm install axios 创建单页组件UserInfo.vue <template> <div class="userList"> <el-button type="primary" @click="handleClick">获取服务端时间</el-button> <p>call from server:{{msg}}</p> </div> </template> <script> import axios from 'axios'; export default{ data(){ return { msg:"" } }, methods: { handleClick(evt) { let _self=this; axios.get('http://localhost:5000/api/Values') .then(function (response) { //debugger; console.log(response); _self.msg=response.data; }) .catch(function (error) { console.log(error); }); } } } </script> <style scoped> .userList { padding-top: 10px; } </style> 运行效果 npm run dev 注意:response的 original ,这可是cors的关键所在 原文发布时间:2018-6-19 原文作者:dotNET跨平台 本文来源掘金如需转载请紧急联系作者

优秀的个人博客,低调大师

高德地图web端笔记;发送http请求的工具类

1.查询所有电子围栏 package com.skjd.util; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; public class HttpUtils { // 代理服务器的HTTP请求协议,客户端真实IP字段名称 public static final String X_REAL_IP = "x-forwarded-for"; public static String get(final String url) throws Exception { String result = null; CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpGet httpGet = new HttpGet(url); CloseableHttpResponse response = httpclient.execute(httpGet); try { System.out.println(response.getStatusLine()); HttpEntity entity = response.getEntity(); // do something useful with the response body // and ensure it is fully consumed result = org.apache.http.util.EntityUtils.toString(entity); org.apache.http.util.EntityUtils.consume(entity); } finally { response.close(); } } finally { httpclient.close(); } return result; } public static String post(final String url, final Map<String, String> param) throws Exception { String result = null; CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httpPost = new HttpPost("http://httpbin.org/post"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); for (String key : param.keySet()) { nvps.add(new BasicNameValuePair(key, param.get(key))); } httpPost.setEntity(new UrlEncodedFormEntity(nvps)); CloseableHttpResponse response = httpclient.execute(httpPost); try { System.out.println(response.getStatusLine()); HttpEntity entity = response.getEntity(); // do something useful with the response body // and ensure it is fully consumed result = org.apache.http.util.EntityUtils.toString(entity); org.apache.http.util.EntityUtils.consume(entity); } finally { response.close(); } } finally { httpclient.close(); } return result; } /** * 发送POST请求的方法 */ public static String sendPostRequest(String url,String param){ HttpURLConnection httpURLConnection = null; OutputStream out = null; //写 InputStream in = null; //读 int responseCode = 0; //远程主机响应的HTTP状态码 String result=""; try{ URL sendUrl = new URL(url); httpURLConnection = (HttpURLConnection)sendUrl.openConnection(); //post方式请求 httpURLConnection.setRequestMethod("POST"); //设置头部信息 httpURLConnection.setRequestProperty("headerdata", "ceshiyongde"); //一定要设置 Content-Type 要不然服务端接收不到参数 httpURLConnection.setRequestProperty("Content-Type", "application/Json; charset=UTF-8"); //指示应用程序要将数据写入URL连接,其值默认为false(是否传参) httpURLConnection.setDoOutput(true); //httpURLConnection.setDoInput(true); httpURLConnection.setUseCaches(false); httpURLConnection.setConnectTimeout(30000); //30秒连接超时 httpURLConnection.setReadTimeout(30000); //30秒读取超时 //获取输出流 out = httpURLConnection.getOutputStream(); //输出流里写入POST参数 out.write(param.getBytes()); out.flush(); out.close(); responseCode = httpURLConnection.getResponseCode(); BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),"UTF-8")); result =br.readLine(); }catch(Exception e) { e.printStackTrace(); } return result; } /** * 发送GET请求的方法 */ public static String sendPostRequestGet(String url){ HttpURLConnection httpURLConnection = null; OutputStream out = null; //写 InputStream in = null; //读 int responseCode = 0; //远程主机响应的HTTP状态码 String result=""; try{ URL sendUrl = new URL(url); httpURLConnection = (HttpURLConnection)sendUrl.openConnection(); //post方式请求 httpURLConnection.setRequestMethod("GET"); //设置头部信息 httpURLConnection.setRequestProperty("headerdata", "ceshiyongde"); //一定要设置 Content-Type 要不然服务端接收不到参数 httpURLConnection.setRequestProperty("Content-Type", "application/Json; charset=UTF-8"); //指示应用程序要将数据写入URL连接,其值默认为false(是否传参) httpURLConnection.setDoOutput(true); //httpURLConnection.setDoInput(true); httpURLConnection.setUseCaches(false); httpURLConnection.setConnectTimeout(30000); //30秒连接超时 httpURLConnection.setReadTimeout(30000); //30秒读取超时 responseCode = httpURLConnection.getResponseCode(); BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),"UTF-8")); result =br.readLine(); }catch(Exception e) { e.printStackTrace(); } return result; } /** * for nigx返向代理构造 获取客户端IP地址 * @param request * @return */ public static String getRemoteHost(HttpServletRequest request){ String ip = request.getHeader(X_REAL_IP); if(ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) { ip = request.getRemoteAddr(); } return ip.split(",")[0]; } public static void main(String[] args) { try { System.out.println(get("http://www.baidu.com")); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } http请求工具类 /** * 根据key查询所有的围栏 * 返回所有围栏的信息 * @param pd * @return * @throws Exception */ public List<Map<String,Object>> select(Map<String,Object> pd) throws Exception{ Gson gson=new Gson(); String key=pd.get("key").toString(); String url="http://restapi.amap.com/v4/geofence/meta?key=" +key; //请求返回的参数 String data=HttpUtils.sendPostRequestGet(url); //转为对象便于获取 Map<String,Object> dataJson = gson.fromJson(data, HashMap.class); Map<String, Object> map=(LinkedTreeMap)dataJson.get("data"); List<Map<String,Object>> list = (List)map.get("rs_list"); return list; } 2.创建围栏 /** * 传入对应格式的坐标区域,创建一个围栏;返回status(新增成功0,已存在返回1;失败返回2);若新增成功则返回gid;message信息 */ public static PageData xyUtil(PageData pd){ PageData pd2=new PageData(); pd.put("key", "be8e6c802d51a4be29c99be895d8c2c7"); //数据库读取的坐标参数 /*114.288221,30.593268#114.321866,30.580559#114.311223,30.560015#114.291278,30.602487#*/ //第三方接口要求的格式:lon1,lat1;lon2,lat2;lon3,lat3(3<=点个数<=5000) //将#号换为; String points = pd.getString("points").replace("#", ";"); String key=pd.getString("key"); String name=pd.getString("name1"); PageData pd3=new PageData(); pd3.put("points", points); pd3.put("name", name); /*pd3.put("valid_time ", DateUtil.getDay());设置过期时间、默认90天*/ pd3.put("repeat", "Mon,Tues,Wed,Thur,Fri,Sat,Sun");//可以指定每天的监控时间段和一周内监控的日期 Gson gson=new Gson(); //传入的参数 String param=gson.toJson(pd3); String url="http://restapi.amap.com/v4/geofence/meta?key=" + key + "&type=ajaxRequest"; String data=HttpUtil.sendPostRequest(url,param); //请求回来的数据 System.out.println(data); PageData data2 = gson.fromJson(data, pd.getClass()); PageData data3 = gson.fromJson(data2.get("data").toString(), pd.getClass()); //状态为0说明新增成功! if(data3.get("status").toString().equals("0.0")){ pd2.put("status", "0"); pd2.put("gid", data3.get("gid").toString()); //返回状态106.0说明已存在,则查询此区域的gid }else if(data3.get("status").toString().equals("106.0")){ pd2.put("status", "1"); }else{ pd2.put("status", "2"); } pd2.put("message", data3.get("message").toString()); return pd2; } 3.更新围栏 /** * 更新围栏;传入围栏名称name;gid;传入围栏坐标点points * @param pd * @return 返回status */ public static PageData xyupdata(PageData pd){ PageData pd2=new PageData(); pd.put("key", "be8e6c802d51a4be29c99be895d8c2c7"); String key=pd.getString("key"); /* String gid=pd.getString("gid");*/ String gid=pd.getString("gid"); pd2.put("repeat", "Mon,Tues,Wed,Thur,Fri,Sat,Sun"); pd2.put("points",pd.getString("points").replace("#", ";")); pd2.put("name", pd.getString("name1")); Gson gson=new Gson(); //传入的参数 String param=gson.toJson(pd2); String url="http://restapi.amap.com/v4/geofence/meta?key=" + key+"&gid=" +gid + "&type=ajaxRequest&method=patch"; String data=HttpUtil.sendPostRequest(url,param); System.out.println(data); PageData data2 = gson.fromJson(data, pd.getClass()); PageData data3 = gson.fromJson(data2.get("data").toString(), pd.getClass()); return data3; } 4.删除围栏 /** * 删除围栏;传入围栏名称gid; * @param pd * @return 返回status */ public static PageData xydel(PageData pd){ PageData pd2=new PageData(); pd.put("key", "be8e6c802d51a4be29c99be895d8c2c7"); String key=pd.getString("key"); /* String gid=pd.getString("gid");*/ String gid=pd.getString("gid"); Gson gson=new Gson(); //传入的参数 String param=gson.toJson(pd2); String url="http://restapi.amap.com/v4/geofence/meta?key=" + key+"&gid=" +gid + "&type=ajaxRequest&method=delete"; String data=HttpUtil.sendPostRequest(url,param); System.out.println(data); PageData data2 = gson.fromJson(data, pd.getClass()); PageData data3 = gson.fromJson(data2.get("data").toString(), pd.getClass()); return data3; } 5.查询一个坐标是否在围栏内;如果需要查询是否在指定的围栏内,需要做进一步处理 /**需要传入参数key;diu(唯一设备号);时间戳;坐标点 *返回 状态status(0表示在范围内;1表示不在范围内) *如果在范围内,则返回围栏列表,带有gid和name * @throws Exception */ public Map<String,Object> xyTest(Map<String,Object> pd) throws Exception{ Map<String,Object> pd2=new HashMap(); //坐标点 String locations =pd.get("locations").toString(); //key String key=pd.get("key").toString(); //设备唯一标识 String diu=pd.get("diu").toString(); //时间戳 String time="1484816232"; Gson gson=new Gson(); String url="http://restapi.amap.com/v4/geofence/status?" + "key="+key + "&diu="+diu + "&locations="+locations+"," + time; //请求返回的参数 String data=HttpUtils.sendPostRequestGet(url); //转为对象便于获取 Map<String,Object> dataJson = gson.fromJson(data, HashMap.class); Map<String, Object> map=(LinkedTreeMap)dataJson.get("data"); //获取围栏事件列表;如果为空说明不在围栏内 if(map.get("fencing_event_list")==null||((List)map.get("fencing_event_list")).size()<1){ pd2.put("status", "1"); return pd2; } //如果不为空,则获取里面的返回值 List<Map<String,Object>> list = (List) map.get("fencing_event_list"); List<Map<String,Object>> list2 = new ArrayList<>(); for(int i=0;i<list.size();i++){ Map<String,Object> pd3=new HashMap(); Map<String,Object> map2 = list.get(i); //如果高德地图api返回的状态为in说明在范围内 if(map2.get("client_status").toString().equals("in")){ //围栏信息 Map<String,Object> map3 =(Map)map2.get("fence_info"); //添加全局围栏gid值; pd3.put("fence_gid",map3.get("fence_gid").toString()); //添加围栏名称 pd3.put("fence_name", map3.get("fence_name").toString()); list2.add(pd3); } } //添加状态值 pd2.put("status", "0"); pd2.put("list", list2); return pd2; }

优秀的个人博客,低调大师

基于hi-nginx的web开发(python篇)——路由装饰器

现在,有了起步的基本认识,现在需要一个可以媲美flask或者bottle的简洁易用的路由功能,可以用装饰器写法任意映射 URLs 到代码。 这个,并不难。首先,来一个叫做hi的模块:hi.py: 1 import re 2 3 class hi: 4 def __init__(self): 5 self.uri_map={} 6 self.uri_regex_map={} 7 8 def route(self,pattern,method): 9 def wrapper_a(func): 10 self.uri_map[pattern]={'method':method,'callback':func} 11 self.uri_regex_map[pattern]=re.compile(pattern) 12 def wrapper_b(req,res,param): 13 func(req,res,param) 14 return wrapper_b 15 return wrapper_a 16 17 def run(self,req,res): 18 for k,v in self.uri_map.items(): 19 if req.method() in v['method']: 20 m=self.uri_regex_map[k].match(req.uri()) 21 if m: 22 v['callback'](req,res,m.groupdict()) 23 break 把它和index.py放在同一个目录中。以下就是使用路由装饰器后的新代码: 1 import sys 2 sys.path.append('/usr/local/nginx/python') 3 4 from hi import hi 5 app =hi() 6 7 @app.route(r'^/test/?$',['GET','POST']) 8 @app.route(r"^/$",['GET']) 9 def hello_world(req,res,param): 10 res.header('Content-Type','text/plain;charset=utf-8') 11 res.content('hello,world') 12 res.status(200) 13 14 @app.route(r"^/client/?$",['GET','POST']) 15 def client(req,res,param): 16 res.content('{}<br>{}<br>{}<br>{}<br>{}'.format(req.client(),req.method(),req.uri(),req.user_agent(),req.param())) 17 res.status(200) 18 19 @app.route(r"^/hello/(?P<who>\w+)?$",['GET']) 20 def hello(req,res,param): 21 res.content('{}={}'.format('who',param['who'])) 22 res.status(200) 23 24 25 26 if __name__ == '__main__': 27 app.run(hi_req,hi_res) 是不是跟些flask或者bottle一样简单?而且还快得多喔! 访问http://localhost:8080/,http://localhost:8080/client?a=90,http://localhost:8080/hello/cnblogs即可查看结果。 当然,也可以先安装hi.py:https://github.com/webcpp/hi.py 这样的话,上面代码的第1,2行就可以免了。

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册