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

PHP cURL调用ArcGIS API返回HTTP 400错误,浏览器请求正常

解决PHP cURL调用ArcGIS findAddressCandidates API返回HTTP 400错误的问题

问题根源

核心问题是URL参数未做URL编码:浏览器会自动对URL中的特殊字符(空格、中文、标点等)进行编码,但PHP cURL不会自动处理这类字符。当$comune或$address_param包含这类字符时,直接拼接出的URL不符合HTTP规范,服务器就会返回400错误请求。

另外原函数未检查HTTP响应状态码——即使返回400,curl_exec仍会返回服务器的错误响应内容,导致你无法第一时间定位问题。

修复方案

1. 对URL参数进行编码

用urlencode()函数处理$comune和$address_param,确保URL格式合法:

$encoded_comune = urlencode($comune);
$encoded_address = urlencode($address_param);
$geo_request = callAPI_GET("https://geocode-api.arcgis.com/arcgis/rest/services/World/GeocodeServer/findAddressCandidates?city={$encoded_comune}&SingleLine={$encoded_address}&sourceCountry=ITA&maxLocations=1&f=json&outFields=location&token=*MY TOKEN*");

2. 优化cURL函数,增加HTTP状态码检查

修改callAPI_GET函数,添加状态码判断,方便排查错误:

function callAPI_GET($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($curl);
    
    // 获取HTTP响应状态码
    $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    
    if ($result === false) {
        $error = "请求执行错误: " . curl_error($curl);
        curl_close($curl);
        return $error;
    }
    
    // 检查状态码是否为正常范围(2xx)
    if ($http_code < 200 || $http_code >= 300) {
        $error = "服务器返回错误状态码: {$http_code},响应内容: {$result}";
        curl_close($curl);
        return $error;
    }
    
    curl_close($curl);
    return $result;
}

额外优化建议

推荐用http_build_query()构建查询字符串,它会自动对所有参数做URL编码,无需手动处理,更安全高效:

$params = [
    'city' => $comune,
    'SingleLine' => $address_param,
    'sourceCountry' => 'ITA',
    'maxLocations' => 1,
    'f' => 'json',
    'outFields' => 'location',
    'token' => '*MY TOKEN*'
];
$query_string = http_build_query($params);
$url = "https://geocode-api.arcgis.com/arcgis/rest/services/World/GeocodeServer/findAddressCandidates?{$query_string}";
$geo_request = callAPI_GET($url);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 15:52:15