Alternative connection for WebService

2

Good afternoon!

I have the following function:

function API($conteudoAEnviar) {
    try{
        $cabecalho = array(
                'Content-Type: application/json',
                'Authorization: Basic ' . base64_encode(TOTVS_JSON_USER_SECRET . ':' . TOTVS_JSON_PASSWORD_SECRET)
            );

        $ch = curl_init(TOTVS_URL_REST);

            $tpRequisicao = 'POST';

        if ($tpRequisicao == 'POST') {
            curl_setopt($ch, CURLOPT_POST, 1);

            curl_setopt($ch, CURLOPT_POSTFIELDS, $conteudoAEnviar);
        }

        if (!empty($cabecalho)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $cabecalho);
        }

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $resposta = curl_exec($ch);

        curl_close($ch);
    }catch(Exception $e){
        return $e->getMessage();
    }
    return $resposta;
}

So, I need to create a form for when the $ response has an error or failure, either connection or anything, that I can change to a local connection to the database, could give me a light on this, I did not find anything in the searches. Is there a function that verifies that the connection was successful?

    
asked by anonymous 03.09.2018 / 22:01

1 answer

0

It checks with curl_error($ch) , if it fails, throws an exception throw new Exception($error_msg, 1) , treats the exception, trying a new request: something like:

function API($conteudoAEnviar) {
        try {
            $cabecalho = array(
                'Content-Type: application/json',
                'Authorization: Basic ' . base64_encode(TOTVS_JSON_USER_SECRET . ':' . TOTVS_JSON_PASSWORD_SECRET)
            );

            $ch = curl_init(TOTVS_URL_REST);
            $tpRequisicao = 'POST';

            if ($tpRequisicao == 'POST') {
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $conteudoAEnviar);
            }

            if (!empty($cabecalho)) {
                curl_setopt($ch, CURLOPT_HTTPHEADER, $cabecalho);
            }

            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            $resposta = curl_exec($ch);

            if (curl_error($ch)) {
                $error_msg = curl_error($ch);
                throw new Exception($error_msg, 1);
            }

            curl_close($ch);

        } catch (Exception $e) {

            try {
                echo "Inplementar aqui a outra chamada";
            } catch (Exception $e) {
                echo $e->getMessage();
            }
        }
}
    
11.10.2018 / 00:59