/java/

JEE and Retrofit (Wildfly 10.1.0.Final)

2017-09-21 00:44:15

/pom.xml


<dependency>
<groupid>com.squareup.retrofit2</groupid>
<artifactid>retrofit</artifactid>
<version>2.3.0</version>
</dependency>

<dependency>
<groupid>com.squareup.retrofit2</groupid>
<artifactid>converter-gson</artifactid>
<version>2.3.0</version>
</dependency>

/src/main/java/pl/btbw/client/ClientService.java

package pl.btbw.client;

import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import javax.ejb.Stateless;
import java.io.IOException;
import java.util.List;

@Stateless
public class ClientService {

    public void test() {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api.github.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        GitHubService service = retrofit.create(GitHubService.class);

        Call

<list<repodto>&gt; repos = service.listRepos("szalek");

        try {

            Response<list<repodto>&gt; execute = repos.execute();

            List<repodto> body = execute.body();

            for (RepoDto repoDto : body) {
                System.out.println(repoDto);
            }

        } catch (IOException e) {

        }
    }

}

/src/main/java/pl/btbw/client/GitHubService.java

package pl.btbw.client;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;

import java.util.List;

public interface GitHubService {

    @GET("users/{user}/repos")
    Call<list<repodto>&gt; listRepos(@Path("user") String user);
}

/src/main/java/pl/btbw/client/RepoDto.java

package pl.btbw.client;

public class RepoDto {
    public Integer id;

    @Override
    public String toString() {
        return "RepoDto{" +
                "id=" + id +
                '}';
    }
}

/src/main/java/pl/btbw/client/TestController.java

package pl.btbw.client;

import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;

@Path("/test")
public class TestController {

    @Inject
    private ClientService clientService;

    @GET
    @Path("/")
    public String test() {
        clientService.test();
        return "ok";
    }

}