gpt4 book ai didi

c# - 格式化 ESRI 地理编码器的 RestSharp 请求

转载 作者:太空宇宙 更新时间:2023-11-03 12:43:20 25 4
gpt4 key购买 nike

我有一些代码使用 RestSharp 格式化 JSON 请求以访问 ESRI 地理编码 API。代码有效,但我想知道是否有更好的方法将请求转换为正确的格式,这里是我所拥有的示例,下面是请求应该是什么样子的示例。

request = new RestRequest("geocodeAddresses", Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");

//Format the request properly
var attributes = new Dictionary<string, object>();
attributes.Add("OBJECTID", address.Address);
attributes.Add("Address", address.Address);
attributes.Add("City", address.City);
attributes.Add("Region", address.State);
attributes.Add("Postal", address.ZipCode);

JsonObject attributesObj = new JsonObject();
foreach (var parms in attributes)
{
attributesObj.Add(parms);
}


JsonObject recordsObj = new JsonObject();
recordsObj.Add("attributes", attributesObj);
JsonArray EsriRequest = new JsonArray();
EsriRequest.Add(recordsObj);
JsonObject addressObj = new JsonObject();
addressObj.Add("records", EsriRequest);




request.AddParameter("addresses",
addressObj.ToString());
request.AddParameter("token", esriToken.ToString());
request.AddParameter("f", "json");
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
IRestResponse<EsriAddress> responseData = client.Execute<EsriAddress>(request);

请求输出样本:

http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/geocodeAddresses?addresses={"records":[{"attributes":{"OBJECTID":1,"Address":"380 New York St.","City":"Redlands","Region":"CA","Postal":"92373"}},{"attributes":{"OBJECTID":2,"Address":"1 World Way","City":"Los Angeles","Region":"CA","Postal":"90045"}}]}&sourceCountry=USA&token=<YOUR TOKEN>&f=pjson

我目前只发送一个地址,但理论上 api 一次可以接收多个地址。

最佳答案

以下是我如何将一批地址发送到 ArcGIS REST API 中的 geocodeAddresses 方法.我没有使用 RestSharp,只是 HttpClient :

string token = GetToken();
string url = "http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/geocodeAddresses";

using (var client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
var values = new[]
{
new KeyValuePair<string, string>("token", token),
new KeyValuePair<string, string>("forStorage", "true"),
new KeyValuePair<string, string>("MaxBatchSize", "1000"),
new KeyValuePair<string, string>("outFields", "*"),
new KeyValuePair<string, string>("f", "json"),
new KeyValuePair<string, string>("addresses", inputJson) // json string containing an array of a complex type
};

foreach (var keyValuePair in values)
content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);

var response = await client.PostAsync(url, content);
Task<string> responseString = response.Content.ReadAsStringAsync();
string outputJson = await responseString;
}
}

关于c# - 格式化 ESRI 地理编码器的 RestSharp 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38151793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com