一、AGS server admin api 介绍

1.1什么是admin api

AGS Server Admin api 官方的称呼是 AGS Server administrator api, 通过这名字也可以猜出该api的作用,通过该api可以管理arcgis server。ArcGIS Server常见的管理功能有安装配置、server 日志、站点的监测配置等,详细的Server管理内容,可以参考ArcGIS Server的官方帮助的管理arcgis Server。

1.2 admin api 作用

通常ArcGIS Server的管理是通过在manager页面中进行的。但是arcgis server manager所呈现的管理功能其后台也是通过调用admin api。也就是说manager页面的管理是esri通过调用admin api开发出来的web 端的server管理工具。有些server的管理工具在manager找不到,但是可以从admin中页面中获得。

通过调研admin api 完全可以开发一个管理工具来替代manager,从中根据自己的业务需求定制所需要的功能。一句话概括就是使用admin api可以二次开发出server管理系统。目前使用admin api开发比较好的产品为,捷泰天域开发的oneMap,其就是一个通过调用admin api开发出的server管理工具,通过oneMap可以方便的实现manger 已有的功能,也可以实现诸如日志统计分析、管理数据的统计,并将统计信息已图表的形式呈现这种manger没有呈现的功能。

如果用户不想基于admin api 开发新的server管理系统,而想对ArcGIS server manager中的内容进行更改,可以直接进行admin页面中,链接格式如下:http://localhost:6080/arcgis/admin/login,可以在这里面对manager进行管理。

Tips: 10.2  server的admin 中添加了站点的备份与恢复

1.3 admin api的实质

admin api 的实质也就是rest api,通过发送参数为json格式的http请求,实现操作。则可以看出,只要任何可以发送http请求的编程语言都可以用来调用admin api,像java,python,c# 等,本文就采用C# 调用Admin api进行示例。

二、使用C#调用admin api

admin api 通常调用遵循以下步骤:

1.获取token

根据站点用户名和密码生成token和证书

  private string GenerateAGSToken(){try{string urlGenerateToken = string.Format("{0}/generateToken", this.urlRestAdmin);string credential = string.Format("username={0}&password={1}&client=requestip&expiration=&f=json", this.username, this.password);string result = this.GetResult(urlGenerateToken, credential);JsonObject jsonObject = new JsonObject(result);string token = null;if (!jsonObject.Exists("token") || !jsonObject.TryGetString("token", out token)){throw new Exception("Token not found!");}return token;}catch(Exception ex){return string.Empty;}}

View Code

2.构建json格式的参数

根据执行的操作所需要的参数,构建json格式的参数,这里以创建服务操作作为例子,进行json字符串的构建。这里使用的JsonObject对象为SOE开发中的链接库ESRI.ArcGIS.SOESupport.dll 所带。

  public bool CreateService(){try{string token = this.GenerateAGSToken();string serviceUrl = this.urlRestAdmin + "/services/createService";JsonObject jsonObject = new JsonObject();jsonObject.AddString("serviceName", "Test");//服务类型jsonObject.AddString("type", Enum.GetName(typeof(ServiceType), ServiceType.GPServer));jsonObject.AddString("description", "This is an example");//不同的服务类型,其capabilities是不同的,地图服务的为Map,query和data//  jsonObject.AddString("capabilities", "Map,Query,Data");
jsonObject.AddString("capabilities","Uploads");//gp 服务的capabilitiesjsonObject.AddString("clusterName", "default");jsonObject.AddLong("minInstancesPerNode", 1);jsonObject.AddLong("maxInstancesPerNode", 2);jsonObject.AddLong("maxWaitTime", 60);jsonObject.AddLong("maxStartupTime", 300);jsonObject.AddLong("maxIdleTime", 1800);jsonObject.AddLong("maxUsageTime", 600);jsonObject.AddLong("recycleInterval", 24);jsonObject.AddString("loadBalancing", Enum.GetName(typeof(LoadBalancing), LoadBalancing.ROUND_ROBIN));jsonObject.AddString("isolationLevel", Enum.GetName(typeof(IsolationLevel), IsolationLevel.HIGH));JsonObject jsonObjectProperties = new JsonObject();// see for a list complete http://resources.arcgis.com/en/help/server-admin-api/serviceTypes.htmljsonObjectProperties.AddLong("maxBufferCount", 100); // optional 100jsonObjectProperties.AddString("virtualCacheDir", this.urlRestServer + "/arcgiscache"); // optionaljsonObjectProperties.AddLong("maxImageHeight", 2048); // optional 2048jsonObjectProperties.AddLong("maxRecordCount", 1000); // optional 500//10.1中服务是通过msd的形式发布的,所以创建地图服务时候将mxd转换成msd的形式,创建msd的形式而其他服务的数据发布形式,参考上面的链接//  jsonObjectProperties.AddString("filePath", @"C:\AvGis\Test\mappa\UTM_ReteFognaria.msd"); //地图服务 required
                        jsonObjectProperties.AddString( "toolbox",@"d:\Buffer.tbx");//gp服务使用的是路径创建gp服务的路径
jsonObjectProperties.AddLong("maxImageWidth", 2048); // optional 2048jsonObjectProperties.AddBoolean("cacheOnDemand", false); // optional falsejsonObjectProperties.AddString("virtualOutputDir", this.urlRestServer + "/arcgisoutput");jsonObjectProperties.AddString("outputDir", @"C:\arcgisserver\directories\arcgisoutput");jsonObjectProperties.AddString("jobsDirectory", @"C:\arcgisserver\directories\arcgisjobs");                                                                             // requiredjsonObjectProperties.AddString("supportedImageReturnTypes", "MIME+URL"); // optional MIME+URLjsonObjectProperties.AddBoolean("isCached", false); // optional falsejsonObjectProperties.AddBoolean("ignoreCache", false); // optional false jsonObjectProperties.AddBoolean("clientCachingAllowed", false); // optional true jsonObjectProperties.AddString("cacheDir", @"C:\arcgisserver\directories\arcgiscache"); // optional
jsonObject.AddJsonObject("properties", jsonObjectProperties);string result = this.GetResult(serviceUrl, "service=" +HttpUtility.UrlEncode(jsonObject.ToJson()) + "&f=json&token=" + token);return this.HasSuccess(result);}catch{return false;}}

View Code

admin api中的各项参数,详见admin api的帮助:http://resources.arcgis.com/en/help/server-admin-api/,参数分为required和optional。

3.发送http请求

admin api可以支持两者get和post请求。server管理功能中有些操作是不支持get请求的。

get请求

  private string GetResult(string url){try{WebRequest request = WebRequest.Create(url);WebResponse response = request.GetResponse();using (Stream responseStream = response.GetResponseStream()){using (StreamReader reader = new StreamReader(responseStream)){return reader.ReadToEnd();}}}catch{throw;}}

View Code

post请求

rivate string GetResult(string url, string postContent){try{WebRequest request = WebRequest.Create(url);byte[] content = Encoding.UTF8.GetBytes(postContent);request.ContentLength = content.Length;request.ContentType = "application/x-www-form-urlencoded";request.Method = WebRequestMethods.Http.Post;using (Stream requestStream = request.GetRequestStream()){requestStream.Write(content, 0, content.Length);requestStream.Close();WebResponse response = request.GetResponse();using (Stream responseStream = response.GetResponseStream()){using (StreamReader reader = new StreamReader(responseStream)){return reader.ReadToEnd();}}}}catch{throw;}}

View Code

4.接收请求

三、完整的代码

代码中涉及到服务的发布、删除、文件夹的创建等

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;/////////namespace Studioat.ArcGIS.Server.Administrator
{using System;using System.Collections;using System.Collections.Generic;using System.IO;using System.Linq;using System.Net;using System.Text;using System.Web;using ESRI.ArcGIS.SOESupport;/// <summary>/// 服务类型/// </summary>public enum ServiceType{MapServer,GeocodeServer,SearchServer,IndexingLauncher,IndexGenerator,GeometryServer,GeoDataServer,GPServer,GlobeServer,ImageServer}/// <summary>/// 负载平衡/// </summary>public enum LoadBalancing{ROUND_ROBIN,FAIL_OVER}/// <summary>/// isolation level/// /// </summary>public enum IsolationLevel{LOW,HIGH}/// <summary>/// administrative API Rest/// </summary>public class AGSAdmin{private string username;private string password;private string urlRestAdmin;private string urlRestServer;/// <summary>/// Initializes a new instance of the <see cref="AGSAdmin"/> class./// </summary>/// <param name="serverName">server name</param>/// <param name="port">port of server</param>/// <param name="username">username administrator</param>/// <param name="password">password administrator</param>public AGSAdmin(string serverName, int port, string username, string password){this.username = username;this.password = password;string url = string.Format("http://{0}:{1}/arcgis", serverName, port.ToString());this.urlRestAdmin = url + "/admin";this.urlRestServer = url + "/server";}/// <summary>/// Prevents a default instance of the <see cref="AGSAdmin"/> class from being created./// </summary>private AGSAdmin(){}/// <summary>/// Create arcgis server folder/// </summary>/// <param name="folderName">Folder name</param>/// <param name="description">Description of the folder</param>/// <returns>True if successfully created</returns>public bool CreateServerFolder(string folderName, string description){try{string token = this.GenerateAGSToken();string folderUrl = this.urlRestAdmin + "/services/" + folderName + "?f=json&token=" + token;string resultExistsFolder = this.GetResult(folderUrl);if (!this.HasError(resultExistsFolder)){return true; // exists
                }else{string createFolderUrl = this.urlRestAdmin + "/services/createFolder";string postContent = string.Format("folderName={0}&description={1}&f=json&token={2}", folderName, description, token);string result = this.GetResult(createFolderUrl, postContent);return this.HasSuccess(result);}}catch{return false;}}/// <summary>/// Get physical Path and virtual Path from directory ags/// </summary>/// <param name="directory">directory ags</param>/// <param name="physicalPath">physical Path</param>/// <param name="virtualPath">virtual Path</param>/// <returns>True if successfully return path</returns>public bool GetServerDirectory(string directory, out string physicalPath, out string virtualPath){physicalPath = null;virtualPath = null;try{string token = this.GenerateAGSToken();string directoryUrl = this.urlRestAdmin + "/system/directories/" + directory + "?f=json&token=" + token;string result = this.GetResult(directoryUrl);JsonObject jsonObject = new JsonObject(result);if (!jsonObject.Exists("physicalPath") || !jsonObject.TryGetString("physicalPath", out physicalPath)){throw new Exception();}jsonObject = new JsonObject(result);if (!jsonObject.Exists("virtualPath") || !jsonObject.TryGetString("virtualPath", out virtualPath)){throw new Exception();}return true;}catch{return false;}}/// <summary>/// Delete Service/// </summary>/// <param name="serviceName">Service Name</param>/// <param name="serviceType">Server Type</param>/// <returns>True if successfully deleted</returns>public bool DeleteService(string serviceName, ServiceType serviceType){try{string token = this.GenerateAGSToken();string serviceUrl = this.urlRestAdmin + "/services/" + serviceName + "." + Enum.GetName(typeof(ServiceType), serviceType) + "/delete";string result = this.GetResult(serviceUrl, "f=json&token=" + token);return this.HasSuccess(result);}catch{return false;}}/// <summary>/// Start Service/// </summary>/// <param name="serviceName">Service Name</param>/// <param name="serviceType">Server Type</param>/// <returns>True if successfully started</returns>public bool StartService(string serviceName, ServiceType serviceType){try{string token = this.GenerateAGSToken();string serviceUrl = this.urlRestAdmin + "/services/" + serviceName + "." + Enum.GetName(typeof(ServiceType), serviceType) + "/start";string result = this.GetResult(serviceUrl, "f=json&token=" + token);return this.HasSuccess(result);}catch{return false;}}/// <summary>/// 停止服务/// </summary>/// <param name="serviceName">Service Name</param>/// <param name="serviceType">Server Type</param>/// <returns>True if successfully stopped</returns>public bool StopService(string serviceName, ServiceType serviceType){try{string token = this.GenerateAGSToken();string serviceUrl = this.urlRestAdmin + "/services/" + serviceName + "." + Enum.GetName(typeof(ServiceType), serviceType) + "/stop";string result = this.GetResult(serviceUrl, "f=json&token=" + token);return this.HasSuccess(result);}catch{return false;}}/// <summary>/// 列举服务/// </summary>public void ListServices(){this.ListServices(null);}/// <summary>/// list of services in folder/// </summary>/// <param name="folder">name of folder</param>public void ListServices(string folder){try{string token = this.GenerateAGSToken();string serviceUrl = this.urlRestAdmin + "/services/" + folder;string postcontent = "f=json&token=" + token;string result = this.GetResult(serviceUrl, postcontent);JsonObject jsonObject = new JsonObject(result);object[] folders = null;if (jsonObject.Exists("folders") && jsonObject.TryGetArray("folders", out folders)){foreach (string subfolder in folders){this.ListServices(subfolder);}}object[] services = null;if (jsonObject.Exists("services") && jsonObject.TryGetArray("services", out services)){IEnumerable<JsonObject> jsonObjectService = services.Cast<JsonObject>();jsonObjectService.ToList().ForEach(jo =>{string serviceName;jo.TryGetString("serviceName", out serviceName);string folderName;jo.TryGetString("folderName", out folderName);Console.WriteLine(folderName + "/" + serviceName);});}}catch{throw;}}/// <summary>/// create service type MapServer/// </summary>/// <returns>>True if successfully created</returns>public bool CreateService(){try{string token = this.GenerateAGSToken();string serviceUrl = this.urlRestAdmin + "/services/createService";JsonObject jsonObject = new JsonObject();jsonObject.AddString("serviceName", "Test");//服务类型jsonObject.AddString("type", Enum.GetName(typeof(ServiceType), ServiceType.GPServer));jsonObject.AddString("description", "This is an example");//不同的服务类型,其capabilities是不同的,地图服务的为Map,query和data//  jsonObject.AddString("capabilities", "Map,Query,Data");
jsonObject.AddString("capabilities","Uploads");//gp 服务的capabilitiesjsonObject.AddString("clusterName", "default");jsonObject.AddLong("minInstancesPerNode", 1);jsonObject.AddLong("maxInstancesPerNode", 2);jsonObject.AddLong("maxWaitTime", 60);jsonObject.AddLong("maxStartupTime", 300);jsonObject.AddLong("maxIdleTime", 1800);jsonObject.AddLong("maxUsageTime", 600);jsonObject.AddLong("recycleInterval", 24);jsonObject.AddString("loadBalancing", Enum.GetName(typeof(LoadBalancing), LoadBalancing.ROUND_ROBIN));jsonObject.AddString("isolationLevel", Enum.GetName(typeof(IsolationLevel), IsolationLevel.HIGH));JsonObject jsonObjectProperties = new JsonObject();// see for a list complete http://resources.arcgis.com/en/help/server-admin-api/serviceTypes.htmljsonObjectProperties.AddLong("maxBufferCount", 100); // optional 100jsonObjectProperties.AddString("virtualCacheDir", this.urlRestServer + "/arcgiscache"); // optionaljsonObjectProperties.AddLong("maxImageHeight", 2048); // optional 2048jsonObjectProperties.AddLong("maxRecordCount", 1000); // optional 500//10.1中服务是通过msd的形式发布的,所以创建地图服务时候将mxd转换成msd的形式,创建msd的形式而其他服务的数据发布形式,参考上面的链接//  jsonObjectProperties.AddString("filePath", @"C:\AvGis\Test\mappa\UTM_ReteFognaria.msd"); //地图服务 required
                        jsonObjectProperties.AddString( "toolbox",@"d:\Buffer.tbx");//gp服务使用的是路径创建gp服务的路径
jsonObjectProperties.AddLong("maxImageWidth", 2048); // optional 2048jsonObjectProperties.AddBoolean("cacheOnDemand", false); // optional falsejsonObjectProperties.AddString("virtualOutputDir", this.urlRestServer + "/arcgisoutput");jsonObjectProperties.AddString("outputDir", @"C:\arcgisserver\directories\arcgisoutput");jsonObjectProperties.AddString("jobsDirectory", @"C:\arcgisserver\directories\arcgisjobs");                                                                             // requiredjsonObjectProperties.AddString("supportedImageReturnTypes", "MIME+URL"); // optional MIME+URLjsonObjectProperties.AddBoolean("isCached", false); // optional falsejsonObjectProperties.AddBoolean("ignoreCache", false); // optional false jsonObjectProperties.AddBoolean("clientCachingAllowed", false); // optional true jsonObjectProperties.AddString("cacheDir", @"C:\arcgisserver\directories\arcgiscache"); // optional
jsonObject.AddJsonObject("properties", jsonObjectProperties);string result = this.GetResult(serviceUrl, "service=" +HttpUtility.UrlEncode(jsonObject.ToJson()) + "&f=json&token=" + token);return this.HasSuccess(result);}catch{return false;}}/// <summary>/// check is status is equal success/// </summary>/// <param name="result">result of request</param>/// <returns>True if status is equal success</returns>private bool HasSuccess(string result){JsonObject jsonObject = new JsonObject(result);string status = null;if (!jsonObject.Exists("status") || !jsonObject.TryGetString("status", out status)){return false;}return status == "success";}/// <summary>///错误信息判断/// </summary>/// <param name="result">result of request</param>/// <returns>True if status is equal error</returns>private bool HasError(string result){JsonObject jsonObject = new JsonObject(result);string status = null;if (!jsonObject.Exists("status") || !jsonObject.TryGetString("status", out status)){return false;}return status == "error";}/// <summary>/// get请求/// </summary>/// <param name="url">get 请求url</param>/// <returns>return response</returns>private string GetResult(string url){try{WebRequest request = WebRequest.Create(url);WebResponse response = request.GetResponse();using (Stream responseStream = response.GetResponseStream()){using (StreamReader reader = new StreamReader(responseStream)){return reader.ReadToEnd();}}}catch{throw;}}/// <summary>/// post请求/// </summary>/// <param name="url">请求url</param>/// <param name="postContent">post content</param>/// <returns></returns>private string GetResult(string url, string postContent){try{WebRequest request = WebRequest.Create(url);byte[] content = Encoding.UTF8.GetBytes(postContent);request.ContentLength = content.Length;request.ContentType = "application/x-www-form-urlencoded";request.Method = WebRequestMethods.Http.Post;using (Stream requestStream = request.GetRequestStream()){requestStream.Write(content, 0, content.Length);requestStream.Close();WebResponse response = request.GetResponse();using (Stream responseStream = response.GetResponseStream()){using (StreamReader reader = new StreamReader(responseStream)){return reader.ReadToEnd();}}}}catch{throw;}}/// <summary>/// 产生token/// </summary>/// <returns>返回一个toke,采用默认的过期时间令牌</returns>private string GenerateAGSToken(){try{string urlGenerateToken = string.Format("{0}/generateToken", this.urlRestAdmin);string credential = string.Format("username={0}&password={1}&client=requestip&expiration=&f=json", this.username, this.password);string result = this.GetResult(urlGenerateToken, credential);JsonObject jsonObject = new JsonObject(result);string token = null;if (!jsonObject.Exists("token") || !jsonObject.TryGetString("token", out token)){throw new Exception("Token not found!");}return token;}catch(Exception ex){return string.Empty;}}}
}

View Code

工程文件下载:https://github.com/myyouthlife/blog/tree/master/Studioat.ArcGIS.Server.Administrator

转载于:https://www.cnblogs.com/myyouthlife/p/3348638.html

C# 调用ArcGIS server admin api相关推荐

  1. ArcGIS Server Felx API接入E都市三维地图

    ArcGIS Server Felx API接入E都市三维地图 (本实例只是个人兴趣研究,如果想要应用到商业用途,请联系相关厂家) 通过HttpWatch工具查看E都市网站加载三维地图的方式及原理,能 ...

  2. ArcGIS Server Felx API接入E都市地图

    ArcGIS Server Felx API接入E都市地图 (本实例只是个人兴趣研究,如果想要应用到商业用途,请联系相关厂家) 通过HttpWatch工具查看E都市网站加载三维地图的方式及原理,能够观 ...

  3. Arcgis server Javascript API 官网相当于HelloWorld的完整版

    虽然放暑假了,不过最近依然很忙,一边忙着准备电子设计大赛,一边跟随研究生师兄们要做Arcgis相关内容,看了一本ArcGIS Server JavaScript API的书,结果发现是针对Arcgis ...

  4. ARCGIS API for JS调用ARCGIS Server自定义布局打印服务

    发布ARCGIS Server自定义布局打印服务 1.打印服务 1.1 什么是PrintingTools 服务 1.2 自定义打印服务 1.2.1 什么是自定义打印服务 1.2.2 更新布局模板 1. ...

  5. 手机调用ArcGIS Server发布的Rest地图服务不显示问题

    如果是本地发布的服务,在手机端调用server服务时,访问rest地址主机名要改为IP加端口号(192.168.1.100:6080),而且必须是内网才能访问 "http://192.168 ...

  6. ol调用arcgis server地图服务的query查询

    目录 一.返回的数据类型 二.属性查询 1.全部查询 2.属性字段查询 三.空间查询 1.根据query结果查询 2.点查询 3.线查询 4.面查询 四.补充 1.spatialRel 2.geome ...

  7. 调用ArcGIS Server的GP服务,显示No JSON object could be decoded要怎么解决?

    如果你也想赚钱,实现财务自由,但接触不到优质的人脉和资源,可以到公June浩:成长home,发"资源" ,就会看到我吐血整理的168条保姆级零基础吸金秘籍,跟着我一起亲历毕业5年. ...

  8. C#调用ArcGIS REST服务

    ArcGIS REST API提供了简单.开放的接口来访问和使用ArcGIS Server发布的服务.使用ArcGIS REST API通过URL可以获取和操作每一个服务中的所有资源和操作. 1.使用 ...

  9. arcgis server发布服务地图不显示_ArcGIS API for JS 导出地图,不限制尺寸

    最近在研究 ArcGIS 导出地图功能,折腾了许久,终于完成了. ArcGIS 自带的打印功能 ArcGIS Server 自带了一个打印地图服务. ArcGIS Server 自带打印地图服务 Ar ...

最新文章

  1. vba定义全局变量并赋值_利用VBA代码如何打开任意程序
  2. html_5_小作业1_超链接练习
  3. 【图像超分辨率】Remote Sensing Image Super-resolution: Challenges and Approaches
  4. ie 调试器,类似firebug
  5. python-zip方法
  6. animation 先执行一次 在持续执行_FANUC机器人:先执行指令功能/后执行指令功能介绍与使用方法...
  7. php mvc登陆注册,Asp.Net MVC 5使用Identity之简单的注册和登陆
  8. sorted()函数快速实现字典输出
  9. Android实现仿IOS带清空功能的文本输入框
  10. 计算机未安装flash,win10系统提示未安装Flash的解决方法
  11. Android Studio 4.1中的模板插件
  12. 学术随笔(二):一篇好论文的标准
  13. android接口调试工具
  14. Kubernetes 开发【1】——webhook 实现 API Server 请求拦截和修改
  15. 阿里的敏捷组织和中台策略有何不同?
  16. 微信SDK中含有的支付功能怎么去掉?
  17. JavaScript - H5 网页拨打电话功能、发送短信、发送邮件(支持 HTML 与 JS 形式)点击自动调起手机拨打并填充手机号
  18. 计算机主机能上网玩游戏吗,为什么现在人人都有电脑,还要去网吧玩游戏?
  19. 安装卡巴斯基提示360 safety guard,360 antivirus,360 safe defender
  20. Win7 系统美化知识

热门文章

  1. 最后一个社团换届的感谢和感悟
  2. python_ re模块学习
  3. Aooms_基于SpringCloud的微服务基础开发平台实战_002_工程构建
  4. 微信企业号:shell定时发送图片 到 指定人
  5. ceph的数据存储之路(10) -----ceph对象存储的ls命令实现及思考
  6. ORACLE SEQUENCE 介绍
  7. shell如何将标准错误输出重定向为标准输出
  8. HTML 5 令人期待的 5 项功能
  9. Python 爬虫从入门到进阶之路(七)
  10. 人生中五个遗憾,共勉