How to create JAX-RS REST Service webservice and consume with android application?

Asked

Viewed 705 times

1

I created a JAX-RS REST Service, with a function that returns me a Jsonobject, I can recover this information in the browser through the URL, but I can’t get it back on an android app. How do I properly configure the Web Service so I can access the data in my application?

@GET
@Produces("application/json")
public String getJson() {
    return "{\"estado\":\"São Paulo \",\"nacionalidade\":\"Brasil \",\"nome\":\"Fulano de Tal \"}";
}

Browser response by accessing URL:

{"estado":"Acre ","nacionalidade":"Brasil ","nome":"Fulano de Tal  "}

Android:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);          
    new HttpAsyncTask().execute("http://localhost:8080/Restful/aluno");
}

public static String GET(String url){
    InputStream inputStream = null;
    String result = "";
    try {

        HttpClient httpclient = new DefaultHttpClient();

        HttpResponse httpResponse = httpclient.execute(new HttpGet(url));

        inputStream = httpResponse.getEntity().getContent();

        if(inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Não funcionou!";

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }

    return result;
}

private static String convertInputStreamToString(InputStream inputStream) throws IOException{
    BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while((line = bufferedReader.readLine()) != null)
        result += line;

    inputStream.close();
    return result;

}

private class HttpAsyncTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {

        return GET(urls[0]);
    }
    @Override
    protected void onPostExecute(String result) {
        Log.e("MainActivity", "Tem resultado? "+result.length());
        Toast.makeText(getBaseContext(), "Received: \n" + result, Toast.LENGTH_LONG).show();
   }
}

In Log the result of the size of this recovered string is 0, and the result of Response is:

Connection to http://localhost:8080/refused

I intend not only to retrieve textual information, I want to recover pdfs through this Web Service.

  • 1

    Have you tried using the IP/domain of the machine you are running WS on instead of localhost?

  • That was it @Bruno César I was able to recover, thank you. But regarding the pdf, what is the best way to recover it in the app and store it?

  • Have you tried anything, how to implement the server service? Something in the way to recover in the app or are still looking for ways?

2 answers

2

To consume your WebService you could work the following way:

public class testeREST
{
private String          URL_WS;
//variaveis de contexto
//definiria o metodo a ser acessado no seu webService("Path")
private final String    metodo  = "teste/";

public List<teste> listarTeste() throws Exception
{
   //pegaria a instancia do seu webservice
    ConexaoWebService conexaoWebService = ConexaoWebService.getInstance();

    //validaria a conexão

 }  
}
//aqui você poderia montar sua url de conexao 
URL_WS = "metodos para obter sua url  ex:192.168.0.200:8080/WebserviceTeste;

Then retrieve your JsonObject

String[] resposta = new WebServiceCliente().get(URL_WS + metodo);
    List<Teste> testeWeb = new ArrayList<Teste>();
    if (resposta[0].equals("200"))
    {
 //utilizando o Gson você consegue criar objetos a partir de Strings em Json
        Gson gson = new Gson();
        JsonParser parser = new JsonParser();
        JsonArray array = parser.parse(resposta[1]).getAsJsonArray();

        //cria um novo objeto a ser carregado 
    for (int i = 0; i < array.size(); i++)
        {
            Teste testando= gson.fromJson(array.get(i), Teste.class);

            TesteImportadoWS testeImportadoWS = new TesteImportadoWS (testeImportadoWS .getEstado());
            testeWeb.add(testeImportadoWS );
        }
     return testeWeb;
    }

With this you would have a list loaded with all the data you want coming via WebService to work.

Link to Gson documentation

0


To communicate between the App and the Webservice I modified the Ip/domain that was passed in the Httpasynctask execute() method.

He was like this:

new HttpAsyncTask().execute("http://localhost:8080/Restful/aluno");

What happens is that the android Emulator is running on different IP network, right? So the Android App is on an IP other than Webservice, which is located locally on your machine. Thus, the IP passed earlier was referencing the android’s own IP on the network, when it was to be the Webservice IP.

When starting my Webservice it was running on IP: "192.168.0.3" on port "8080", so I only changed the ip that was "localhost" to the Webservice IP.

new HttpAsyncTask().execute("http://192.168.0.3:8080/Restful/aluno");

The only change was included in the onCreate method below:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    new HttpAsyncTask().execute("http://192.168.0.3:8080/Restful/aluno");
}

Thanks for the help @Caio_césar

Browser other questions tagged

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