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

1

I created a JAX-RS REST Service, with a function that returns me a JsonObject, I can retrieve this information in the browser through the URL , but I can not retrieve it from an android application. How do I correctly configure the Web Service so that 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 \"}";
}

Response in the browser by going to 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 retrieved 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 retrieve pdfs through this Web Service.

    
asked by anonymous 24.06.2015 / 17:47

2 answers

0

To perform the communication between the App and the WebService I modified the Ip / domain that was passed in the execute () method of HttpAsyncTask.

He was like this:

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

What happens is that the android emulator is running on different IP on the network, right? So the Android Application is on a different Ip from the WebService, which is located locally on your machine . So, the IP passed before was referencing the android IP on the network, when it was to be the IP of the WebService.

When I started my WebService it was running on IP: "192.168.0.3" on port "8080", so I just changed the ip that was as "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

    
01.12.2015 / 23:34
2

To consume your WebService you could work as follows:

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% with%

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 JsonObject to work.

Link to Gson documentation

    
24.06.2015 / 18:25