IDHTTP with Delphi - HTTP request failed 401 HTTP / 1.1 401 Unauthorized

1

Good afternoon.

I have an example PUT request code in PHP:

$params["access_token"] = "### Chave de Acesso ###";
$data["Product"]["stock"] = 100;
$url = "https://{api_address}/products/123?".http_build_query($params);
ob_start();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen(json_encode($data)))
);
curl_exec($ch);

And I'm trying to make the same request in Delphi using IDHTTP:

    vToken:= rotina_que_captura_token
    vUrl:= https://clienteexemplo.commercesuite.com.br/web_api/products/89';
    vJsonProduct:= TJSONObject.Create;
    vJSonPut:= TJSONObject.Create;
    vJsonPut.AddPair('stock', '100');
    vJsonProduct.AddPair('Product', vJsonPut);
    vJsonToSend := TStringStream.Create(vJsonProduct.ToString, TEncoding.UTF8);

    lHTTP:= TIdHTTP.Create(nil);
    IdSSLIOHandlerSocketOpenSSL := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
    lHTTP.IOHandler := IdSSLIOHandlerSocketOpenSSL;
    lHTTP.Request.ContentType := 'application/json';
    lHTTP.Request.UserAgent := 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36';
    lHTTP.Request.CustomHeaders.AddValue('Authorization', 'Bearer ' + vToken);
    Result:= lHTTP.Put(vUrl, vJsonToSend);

I always get the error: HTTP request failed 401 HTTP / 1.1 401 Unauthorized

Can anyone tell me what I'm doing wrong?

    
asked by anonymous 09.11.2018 / 19:01

1 answer

0

Good morning, Marcelo!

I saw that in the PHP call, you pass the token as a parameter in the URL:

/products/123?".http_build_query($params);

In the Delphi call, you do not pass the Token in the URL.

vUrl:= 'https://clienteexemplo.commercesuite.com.br/web_api/products/89;'

I do not know the API that is working, but can it be that?

vUrl:= 'https://clienteexemplo.commercesuite.com.br/web_api/products/89?access_token=' + vToken;
    
14.11.2018 / 13:15