我有服务网址:请检查一下,它是返回的json字符串。
我不知道如何使用C#调用这个url
然后。通过链接,您可以在json数据中看到"href"。它有.png网址。我想把这个映像保存到我的本地磁盘。
问题
发布于 2012-03-05 09:10:19
使用数据契约和DataContractJsonSerializer
所需参考资料:
using System.Runtime.Serialization;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Net;数据契约
[DataContract]
internal class GISData
{
[DataMember]
public string href;
[DataMember]
public int width;
[DataMember]
public int height;
[DataMember]
public GISDataExtent extent;
[DataMember]
public string scale;
}
[DataContract]
internal class GISDataExtent
{
[DataMember]
public string xmin;
[DataMember]
public string ymin;
[DataMember]
public string xmax;
[DataMember]
public string ymax;
[DataMember]
public GISDataExtentSpatialReference spatialReference;
}
[DataContract]
internal class GISDataExtentSpatialReference
{
[DataMember]
public string wkid;
}将所有内容放在一起并下载该文件:
从URL中提取JSON字符串-反序列化对象并下载图像。
WebClient webClient;
webClient = new WebClient();
string json = webClient.DownloadString(@"http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/export?bbox=9153621.1267%2C-644273.9207%2C13435472.9966%2C3637577.9492&bboxSR=&layers=&layerdefs=&size=800%2C600&imageSR=&format=png&transparent=false&dpi=&time=&layerTimeOptions=&f=pjson");
MemoryStream stream = new MemoryStream((Encoding.UTF8.GetBytes(json)));
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(GISData));
stream.Position = 0;
GISData data = (GISData)ser.ReadObject(stream);
stream.Close();
webClient = new WebClient();
webClient.DownloadFile(data.href, "C:/" + data.href.Substring(data.href.LastIndexOf("/") + 1)); //Save only the filename and not the entire URL as a name.发布于 2012-03-05 09:02:59
我想您需要的是来自服务器的服务请求,而不是来自客户端的服务请求;如果是这样的话,一个简单的方法是
string json = null;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/export?bbox=9153621.1267%2C-644273.9207%2C13435472.9966%2C3637577.9492&bboxSR=&layers=&layerdefs=&size=800%2C600&imageSR=&format=png&transparent=false&dpi=&time=&layerTimeOptions=&f=pjson");
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
var responseStream = response.GetResponseStream();
if ((responseStream != null) && responseStream.CanRead)
{
using (var reader = new System.IO.StreamReader(responseStream))
{
json = reader.ReadToEnd();
}
}
}
finally
{
if (response != null)
{
response.Close();
}
}图像也可以用同样的方式获得。
对于Json,我推荐JSON.NET。
发布于 2012-03-05 09:22:35
注意,您的png文件不存在:)
如果需要,可以创建POCO类。但是如果你只需要下载一个文件,那可能就不需要了。
https://stackoverflow.com/questions/9563302
复制相似问题