一、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;
}
}

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 服务的capabilities
jsonObject.AddString("clusterName", "default");
jsonObject.AddLong("minInstancesPerNode", );
jsonObject.AddLong("maxInstancesPerNode", );
jsonObject.AddLong("maxWaitTime", );
jsonObject.AddLong("maxStartupTime", );
jsonObject.AddLong("maxIdleTime", );
jsonObject.AddLong("maxUsageTime", );
jsonObject.AddLong("recycleInterval", );
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.html
jsonObjectProperties.AddLong("maxBufferCount", ); // optional 100
jsonObjectProperties.AddString("virtualCacheDir", this.urlRestServer + "/arcgiscache"); // optional
jsonObjectProperties.AddLong("maxImageHeight", ); // optional 2048
jsonObjectProperties.AddLong("maxRecordCount", ); // 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", ); // optional 2048
jsonObjectProperties.AddBoolean("cacheOnDemand", false); // optional false
jsonObjectProperties.AddString("virtualOutputDir", this.urlRestServer + "/arcgisoutput");
jsonObjectProperties.AddString("outputDir", @"C:\arcgisserver\directories\arcgisoutput");
jsonObjectProperties.AddString("jobsDirectory", @"C:\arcgisserver\directories\arcgisjobs"); // required
jsonObjectProperties.AddString("supportedImageReturnTypes", "MIME+URL"); // optional MIME+URL
jsonObjectProperties.AddBoolean("isCached", false); // optional false
jsonObjectProperties.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;
}
}

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;
}
}

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, , content.Length);
requestStream.Close();
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
return reader.ReadToEnd();
}
}
}
}
catch
{
throw;
}
}

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 服务的capabilities
jsonObject.AddString("clusterName", "default");
jsonObject.AddLong("minInstancesPerNode", );
jsonObject.AddLong("maxInstancesPerNode", );
jsonObject.AddLong("maxWaitTime", );
jsonObject.AddLong("maxStartupTime", );
jsonObject.AddLong("maxIdleTime", );
jsonObject.AddLong("maxUsageTime", );
jsonObject.AddLong("recycleInterval", );
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.html
jsonObjectProperties.AddLong("maxBufferCount", ); // optional 100
jsonObjectProperties.AddString("virtualCacheDir", this.urlRestServer + "/arcgiscache"); // optional
jsonObjectProperties.AddLong("maxImageHeight", ); // optional 2048
jsonObjectProperties.AddLong("maxRecordCount", ); // 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", ); // optional 2048
jsonObjectProperties.AddBoolean("cacheOnDemand", false); // optional false
jsonObjectProperties.AddString("virtualOutputDir", this.urlRestServer + "/arcgisoutput");
jsonObjectProperties.AddString("outputDir", @"C:\arcgisserver\directories\arcgisoutput");
jsonObjectProperties.AddString("jobsDirectory", @"C:\arcgisserver\directories\arcgisjobs"); // required
jsonObjectProperties.AddString("supportedImageReturnTypes", "MIME+URL"); // optional MIME+URL
jsonObjectProperties.AddBoolean("isCached", false); // optional false
jsonObjectProperties.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, , 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;
}
}
}
}

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

C# 调用ArcGIS server admin api的更多相关文章

  1. arcgis engine 调用arcgis server服务

    首先需要添加两个引用: using ESRI.ArcGIS.GISClient;using ESRI.ArcGIS.DataSourcesRaster; /// <summary> /// ...

  2. OpenLayers调用arcgis server发布的地图服务

    有两种方式可以调用arcgis server发布的地图服务,一种是rest,一种是wms.  地图的投影为900913,arcgis server为10.0版本,地图服务的空间参考为3857.   与 ...

  3. OpenLayers调用ArcGIS Server发布的WFS服务

    OpenLayers调用ArcGIS Server发布的WFS服务 原创: 蔡建良 2013-08-20 一. 开发环境 1) Openlayers2.13+arcgis server9.3 2) W ...

  4. C#中winform下利用ArcEngine调用ArcGIS Server发布的服务 AE 10

    开发环境:vs2010 + AE 10 测试 public Form1() { ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Engi ...

  5. C#中winform下利用ArcEngine调用ArcGIS Server发布的服务 AE9.3

    主要使用了AE中的IAGSServerOject接口及IMapServer接口.Private void GetServerTest_Click(object sender, EventArgs e) ...

  6. ArcGIS Server JavaScript API 各命名空间的含义【转】

    1.esri 命名空间      所有的对象都是在 esri 命名空间下的,esri 有自己的属性和方法.      如 esri.version 返回当前 JavaScript API 的版本号.e ...

  7. ArcGIS Server JavaScript API中ESRI字体下载

    ---------------------------------------------------------------------------------- import sys, os im ...

  8. 移动端调用ArcGIS Server 10.1服务

    1.最好用mdb数据源,不要用shp文件作为数据源,一是属性字段长度超过5个字符会被截断,二是中文会变成乱码. 2.mxd的layer的坐标系要是WGS1984(4362),不然属性查询不出来.

  9. 应用ArcGIS Server JavaScript API实现地图卷帘效果实现

    var maskDynamicMapServiceLayer = null; var maskDynamicMapServiceLayerDiv = null; var pointNumb = 0; ...

随机推荐

  1. JDK1.9环境变量配置

    JAVA_HOME C:\Program Files\Java\jdk-9.0.1 JRE_HOME C:\Program Files\Java\jre-9.0.1 PATH .;%JAVA_HOME ...

  2. /etc/syslog.conf文件作用

    /etc/syslog.conf配置文件控制syslog daemon的操作规则形式:facility.level actionfacility.level 为选择器,action 指定与选择器匹配的 ...

  3. MySql(零):Linux(CentOS7)下安装和配置MySQL5.7.20(安装包安装)

    一.下载安装包 1.在官网下载MySQL5.7安装包 mysql-5.7.20-linux-glibc2.12-x86_64.tar.gz. 下载地址:https://dev.mysql.com/do ...

  4. 激活modelsim se 10.4 时运行patch_dll.bat不能生成TXT

    问题描述: 激活modelsim时运行patch_dll.bat总是在DOS界面一闪而过,不能生成LICENSE.TXT 问题解决: 先取消文件 mgls64.dll 的只读属性(这句话在README ...

  5. PHP修改memory_limit的三种办法

     PHP修改memory_limit的三种办法 2010-06-11 10:57:11 分类: 可能是分词程序的问题.只要搜索的字段达到十个汉字以上,就会出现诸如以下的错误 Fatal error: ...

  6. 微信小程序新建项目完整流程

    最近刚好也在做新的小程序项目,所以有机会给大家整理一个完整的开发流程! 上一篇介绍是如何获得appid,那么接下来就是怎么新建一个全新的小程序项目了 首先:下载最新版的微信开发者工具,支持网页版微信开 ...

  7. hMailServer 附件大小限制

    修改php.ini文件 1.post_max_size = 10M 表单提交最大数据为10M.此项不是限制上传单个文件的大小,而是针对整个表单的提交数据进行限制的. 2.file_uploads = ...

  8. VS中去除SrouceControl的信息

    如果在不连接TFS的情况下,编辑一个已经source control的solution,总是会有烦人的提示信息.如果你确定不再需要source control,可以这么干. Here is how t ...

  9. HDU高精度总结(java大数类)

      HDU1002   A + B Problem II [题意]大数相加 [链接]http://acm.hdu.edu.cn/showproblem.php?pid=1002 Sample Inpu ...

  10. js动态创建input

    var muiDiv = document.getElementById('mui-content'); createInput('img','text',imgSrc,muiDiv); functi ...