使用c# 操作GeoServer REST
Get方式:
#region 向服务发送Get请求
public string CreateGet(string url)
{
return CreateGet(url, Encoding.UTF8);
}
public string CreateGet(string url, Encoding coding)
{
HttpWebRequest request = null;
HttpWebResponse response = null;
request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "GET";
request.KeepAlive = false;
// 提交请求数据
CredentialCache myCredential = new CredentialCache();
myCredential.Add(new Uri(url), "Basic", new NetworkCredential(usernameWfs, passwordWfs));
request.Credentials = myCredential;
response = request.GetResponse() as HttpWebResponse;
System.IO.Stream responseStream = response.GetResponseStream();
System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, coding);
string srcString = reader.ReadToEnd();
return srcString;
}
#endregion
Post方式:
#region 向服务Post请求
public string CreatePost(string url, string param, string contentType)
{
if (string.IsNullOrEmpty(contentType))
{
contentType = "text/xml";
}
return CreatePost(url, Encoding.UTF8, param, "POST", contentType);
}
public string CreatePost(string url, Encoding coding, string param, string requestMethod, string contentType)
{
HttpWebRequest request = null;
HttpWebResponse response = null;
request = WebRequest.Create(url) as HttpWebRequest;
request.Method = requestMethod;
request.KeepAlive = false;
request.ContentType = contentType;
CredentialCache myCredential = new CredentialCache();
myCredential.Add(new Uri(url), "Basic", new NetworkCredential(usernameWfs, passwordWfs));
request.Credentials = myCredential;
byte[] data = Encoding.UTF8.GetBytes(param);
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
stream.Close();
}
// 接收返回的页面
response = request.GetResponse() as HttpWebResponse;
System.IO.Stream responseStream = response.GetResponseStream();
System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, coding);
string srcString = reader.ReadToEnd();
return srcString;
}
#endregion
代码中的 usernameWfs, passwordWfs是GeoServer的用户名和密码,替换成自己的即可。