You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中含MultipartFormData的ArcGIS Geocoding API请求URL编码求助

解决ArcGIS API要求URL编码的请求问题

原代码使用MultipartFormDataContent提交多部分表单,现在ArcGIS要求采用URL编码格式的请求,可改用FormUrlEncodedContent实现,它会自动完成参数的URL编码,修改后的代码如下:

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

using (var client = new HttpClient())
{
    var values = new List<KeyValuePair<string, string>>
    {
        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字符串包含复杂类型数组
    };

    // 使用FormUrlEncodedContent自动处理URL编码
    using (var content = new FormUrlEncodedContent(values))
    {
        // 设置Content-Type头,确保服务器识别URL编码格式
        content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");

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

核心说明:

  • FormUrlEncodedContent会自动对参数的键和值执行URL编码,完全符合ArcGIS的要求。
  • 替换为FormUrlEncodedContent后,请求的Content-Type会被设为application/x-www-form-urlencoded,这是URL编码表单的标准类型。
  • 若inputJson包含特殊字符(如&、=、空格等),FormUrlEncodedContent也会自动编码,无需手动处理。

如果遇到特殊场景需要手动编码单个参数值,可使用Uri.EscapeDataString()方法:

string encodedInputJson = Uri.EscapeDataString(inputJson);

将编码后的字符串作为参数值传入即可。

内容的提问来源于stack exchange,提问作者harharsar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 14:02:26