-2

I'm trying to call a GET REST API, the problem is that the remote server gives me a HTTP 400 error. But when I put the link to my browser, it returns me the right response. It's something wrong with my code? The API I'm using is ArcGIS findAddressCandidates Here's the function i used:

function callAPI_GET($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    // Execute
    $result = curl_exec($curl);
    if ($result) {
        // Returns result
        return $result;
    } else {
        // Returns error
        return "Errore durante l'esecuzione della richiesta: " . curl_error($curl);
    }
}

Here's the call:

$geo_request = callAPI_GET('https://geocode-api.arcgis.com/arcgis/rest/services/World/GeocodeServer/findAddressCandidates?city=' . $comune . '&SingleLine=' . $address_param . '&sourceCountry=ITA&maxLocations=1&f=json&outFields=location&token=*MY TOKEN*');
lorek006
  • 29
  • 4
  • Do you see any error messages – RiggsFolly Aug 15 '23 at 13:03
  • 1
    Browsers tend to apply missing URL encoding on their own, but cURL doesn't. And I don't see you applying any while assembling that URL either - so depending on the actual parameter values, that could already be the reason. Hint: https://www.php.net/manual/en/function.http-build-query.php exists. – CBroe Aug 15 '23 at 13:06
  • Some sites also check for a User-Agent header as a sort of ultra low-level bot detection. – CBroe Aug 15 '23 at 13:07
  • CBroe's reply solved my problem. The problem probably was in the URL encoding – lorek006 Aug 15 '23 at 13:24
  • Does this answer your question? [How can I emulate a get request exactly like a web browser?](https://stackoverflow.com/questions/2440729/how-can-i-emulate-a-get-request-exactly-like-a-web-browser) – hanshenrik Aug 15 '23 at 18:11

2 Answers2

0

We can only speculate. Maybe the target api has a user-agent whitelist? maybe it only responds 200 to Accept: text/html ? maybe it needs a pre-existing cookie session? whatever the case, see my answer here: https://stackoverflow.com/a/55829622/1067003

or better yet, check the api documentation.

hanshenrik
  • 19,904
  • 4
  • 43
  • 89
-1

it's because of SSL, your localhost doesn't have SSL installed so you have to add curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0)

where verifying your SSL is not required.