一、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", 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.html
jsonObjectProperties.AddLong("maxBufferCount", 100); // optional 100
jsonObjectProperties.AddString("virtualCacheDir", this.urlRestServer + "/arcgiscache"); // optional
jsonObjectProperties.AddLong("maxImageHeight", 2048); // optional 2048
jsonObjectProperties.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 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, 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;
}
}
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;
///
/// 服务类型
///
public enum ServiceType
{
MapServer,
GeocodeServer,
SearchServer,
IndexingLauncher,
IndexGenerator,
GeometryServer,
GeoDataServer,
GPServer,
GlobeServer,
ImageServer
}
///
/// 负载平衡
///
public enum LoadBalancing
{
ROUND_ROBIN,
FAIL_OVER
}
///
/// isolation level
///
///
public enum IsolationLevel
{
LOW,
HIGH
}
///
/// administrative API Rest
///
public class AGSAdmin
{
private string username;
private string password;
private string urlRestAdmin;
private string urlRestServer;
///
/// Initializes a new instance of the class.
///
/// server name
/// port of server
/// username administrator
/// password administrator
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";
}
///
/// Prevents a default instance of the class from being created.
///
private AGSAdmin()
{
}
///
/// Create arcgis server folder
///
/// Folder name
/// Description of the folder
/// True if successfully created
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;
}
}
///
/// Get physical Path and virtual Path from directory ags
///
/// directory ags
/// physical Path
/// virtual Path
/// True if successfully return path
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;
}
}
///
/// Delete Service
///
/// Service Name
/// Server Type
/// True if successfully deleted
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;
}
}
///
/// Start Service
///
/// Service Name
/// Server Type
/// True if successfully started
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;
}
}
///
/// 停止服务
///
/// Service Name
/// Server Type
/// True if successfully stopped
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;
}
}
///
/// 列举服务
///
public void ListServices()
{
this.ListServices(null);
}
///
/// list of services in folder
///
/// name of folder
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 jsonObjectService = services.Cast();
jsonObjectService.ToList().ForEach(jo =>
{
string serviceName;
jo.TryGetString("serviceName", out serviceName);
string folderName;
jo.TryGetString("folderName", out folderName);
Console.WriteLine(folderName + "/" + serviceName);
});
}
}
catch
{
throw;
}
}
///
/// create service type MapServer
///
/// >True if successfully created
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", 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.html
jsonObjectProperties.AddLong("maxBufferCount", 100); // optional 100
jsonObjectProperties.AddString("virtualCacheDir", this.urlRestServer + "/arcgiscache"); // optional
jsonObjectProperties.AddLong("maxImageHeight", 2048); // optional 2048
jsonObjectProperties.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 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;
}
}
///
/// check is status is equal success
///
/// result of request
/// True if status is equal success
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";
}
///
///错误信息判断
///
/// result of request
/// True if status is equal error
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";
}
///
/// get请求
///
/// get 请求url
/// return response
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请求
///
/// 请求url
/// post content
///
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;
}
}
///
/// 产生token
///
/// 返回一个toke,采用默认的过期时间令牌
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