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

Asked

Viewed 758 times

1

Good afternoon.

I have an example of PHP PUT request code:

$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);

Always returns the error: HTTP request failed 401 HTTP/1.1 401 Unauthorized

Can anyone tell me what I’m doing wrong ?

1 answer

0


Good morning, Marcelo!

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

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

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

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

I don’t know the API you’re working on, but could that be it?

vUrl:= 'https://clienteexemplo.commercesuite.com.br/web_api/products/89?access_token=' + vToken;
  • 1

    Good afternoon Cleber. That was it. Thank you very much.

  • Happy to help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.