Handling JSON with JAVA

Asked

Viewed 1,406 times

2

Through JAVA, I need to make a request via POST, where I will get a JSON with a token. The JSON return I get after sending the POST is this:

    {
        "Token": "e27bb0a7-e65b-4cc3-a82e-7a2a3c26a248",
        "Codigo": 0
    }

How do I do this process in java without using controller and ajax?

In Javascript was made this way:

$(document).ready(function() {

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "https://siteexemplo.br/login/geraTok",
  "method": "POST",
  "headers": {
    "content-type": "application/json",
  },
  "data": {
    "RA": "12345",
    "senha": "xxx"
  }
}

$.ajax(settings).done(function (response) {
    var token = response.Token;
});

});

3 answers

2

To turn the result into an object, we can use the library GSON

Follow the download link

To make the request, we use Httpsurlconnection

Follow an example:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;

public class DecodeJson {

       public static void main(String[] args){

        try {

            /**
             * Vamos criar a conexão com com a URL....
             */
            final URL url = new URL("https://api.myjson.com/bins/11dn6r");

            final HttpsURLConnection connection = HttpsURLConnection.class.cast(url.openConnection());
            /**
             * Informamos que será um POST e será um JSON 
             */
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);
            /**
             * Status da conexão!
             */
            int response = connection.getResponseCode();
            System.out.println("Response code: "+response);
            /*
             * Vamos ler o conteudo....
             */
            final BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuffer buffer = new StringBuffer();
            //Vamos ler linha por linha até o final! 
            while ((inputLine = in.readLine()) != null) {
                buffer.append(inputLine);
            }
            in.close();
            /**
             * Com o resultado, vamos transformar o Objeto!
             */

           final Gson gson = new GsonBuilder().create();
           /**
            * Transformamos o texto em objeto!
            */
           JsonObject  json = gson.fromJson(buffer.toString(), JsonObject.class);
           /**
            * Exibimos os dados...
            */
           System.out.printf(" Token: %s, Código: %d", json.token, json.codigo);
        }catch (final Exception e) {
            e.printStackTrace();
        }

       }


       /**
        * Classe representa o objeto de retorno.
        *
        */
      static class JsonObject {
           /**
            * @SerializedName("NOME_DA_PROPRIEDADE")
            * Se a propriedade da Classe for extamente igual ao objeto JSON
            * não se faz necessario esta anotação!
            **/
           @SerializedName("Token")
           public String token;
           @SerializedName("Codigo")
           public Integer codigo;
       }

}

1

Thanks for the personal help!

It worked and the code ended up like this:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.json.simple.JSONObject;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class GeraBoleto{

    private static final Logger logger = Logger.getLogger(GeraBoleto.class);
    private String configpath = Funcoes.getWFRootDir() + "/upload/cadastros/config/";   


    @Execution
    public String executa(){

        String token = null;    

        try {

                String urlServicoAutenticacao = "http://www.siteexemplo.com.br/teste/login/GerarTokenRA";
                try {
                    Map retornoServicoAutenticacao = getToken("ra123", "senha123", urlServicoAutenticacao);

                    if (retornoServicoAutenticacao == null) {
                        logger.error("[ Erro 768 ]");
                        throw new Exception("Integracao - Servico de autenticacao esta OFFLINE: " + urlServicoAutenticacao);
                    }


                   Gson gson = new GsonBuilder().create();

                   JsonObject json = gson.fromJson(retornoServicoAutenticacao.get("mensagemRetorno"), JsonObject.class);
                   /**
                    * Exibimos os dados...
                    */
                   token = json.get("Token").toString();

                } catch (Exception e) {
                    logger.error("[ Integracao - Servico de autenticacao esta OFFLINE: " + urlServicoAutenticacao + " ]");
                    throw new Exception("Integracao - Servico de autenticacao esta OFFLINE: " + urlServicoAutenticacao);
                }                                                           


        } catch (Exception e) {
            return "99|" + e;
        }

        return "0|" + token;
    }

    /**
     * Metodo responsavel por buscar o token de autenticação para
     * transmissao dos documentos para o cliente     
     */
    public Map getToken(String RA, String senha, String urlServicoAutenticacao)
            throws Exception {

        String mensagemRetorno = null;

        // dados de retorno
        Map retorno = new HashMap();
        // codigo de retorno
        String codigoRetorno = null;

        try {
            URL url = new URL(urlServicoAutenticacao);

            // add header
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            // contemplando o timeout maximo para 1 min, atual 20s
            conn.setReadTimeout(1000 * 20);
            conn.setConnectTimeout(1000 * 20);
            conn.setRequestMethod("POST");
            conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // dados dos parametros
            String urlParameters = "RA=" + RA + "&senha=" + senha;

            // Write data
            OutputStream os = conn.getOutputStream();
            os.write(urlParameters.getBytes());

            os.flush();
            // add o codigo para retorno do metodo
            codigoRetorno = conn.getResponseCode() + "";

            // validando a conexao e o retorno do servico
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                mensagemRetorno = "Falha : HTTP codigo de erro : " + conn.getResponseCode();

                /**
                 * Tratando o retorno com erro
                 */
                BufferedReader br = new BufferedReader(new InputStreamReader((conn.getErrorStream())));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                br.close();
                // JSON de retorno
                mensagemRetorno = sb.toString();
            } else {
                // tratando a resposta diferente de 400 - Bad Request
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                br.close();
                mensagemRetorno = sb.toString();
            }

            conn.disconnect();

        } catch (Exception ex) {
            ex.printStackTrace();
            mensagemRetorno = ex.getMessage();
            logger.error(" ** ERRO - Retorno do servico: " + mensagemRetorno);
        }

        // no caso de erro este valor nao será preenchido
        if (mensagemRetorno != null && !mensagemRetorno.trim().isEmpty()) {
            logger.info(" ** Retorno do servico: " + mensagemRetorno);

            /**
             * Tratando o retorno do JSON
             */
            JsonObject root = new JsonParser().parse(mensagemRetorno).getAsJsonObject();

            // convertendo a lista interna do JSON
            String token = root.get("token") != null ? root.get("token").getAsString() : null;

            // dados para o processo
            retorno.put("codeHTTP", codigoRetorno);
            retorno.put("mensagemRetorno", mensagemRetorno);
            retorno.put("token", token);
        }
        return retorno;
    }


}

0

In a class inherited from Asynctask do this:

    public class RestFulHandler extends AsyncTask<String, String, String> {
        ...
        protected enum OPERACAO{POST, GET};
        private OPERACAO operacao = OPERACAO.POST;

         @Override
         protected String doInBackground(String... strings) {
         try {
           // Create URL
           URL url = new URL("http://suaurl:8080/datasnap/rest/classe/metodo");

           // Create connection
           HttpURLConnection request = (HttpURLConnection) url.openConnection();
           request.setRequestProperty("Content-Type", "application/json");

           if (operacao == OPERACAO.POST) {
             request.setDoInput(true);
             request.setDoOutput(true);
             request.setRequestMethod("POST");
           }
           request.connect();

           if (!operacao.equals(OPERACAO.GET)) { //se for diferente de GET solicitar uma resposta do rest servidor
           OutputStream os = new BufferedOutputStream(request.getOutputStream());
                            os.write(json.getBytes());
                            os.flush();
                            os.close();
                        }

            if (request.getResponseCode() == HttpURLConnection.HTTP_OK) {//tratamento se obeteve resposta do rest servidort

                            InputStream in = new BufferedInputStream(request.getInputStream());

                            BufferedReader reader = null;

                            reader = new BufferedReader(new InputStreamReader(in));
                            String line = "";
                            StringBuffer buffer = new StringBuffer();
                            while ((line = reader.readLine()) != null) {
                                buffer.append(line);
                            }
                            resposta = buffer.toString();

                            in.close();


                        } else {
                            i.Log("erro "+request.getResponseCode()+" "+request.getResponseMessage());
                        }
                        request.disconnect();
                    } catch (MalformedURLException me) {
                        i.Log("MalformedURLException " + me.getMessage());
                    } catch (IOException ioe) {
                        i.Log("IOException " + ioe.getMessage());
                    }
                }
                return resposta;
            }

Browser other questions tagged

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