在 Java 中使用 API 改造用法
Retrofit usage in with API in Java
根据官网的信息,我添加了最新的depedency,开始开发。
首先我用我感兴趣的数据创建了模型:
public class Data{
String parametr1;
//geters and setters ommited
}
第二步是添加服务:
public interface GitHubService {
@GET("/repos/{owner}/{repo}")
Call<Data> repoInfos(@Path("user") String owner, @Path("repo") String repo);
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").build();
}
第三个是添加实现:
@Service
public class GitHubServiceImpl implements GitHubService {
final GitHubService gitHubService = GitHubService.retrofit.create(GitHubService.class);
@Override
public Call<DetailDto> repoDetails(String owner, String repo) {
return gitHubService.repoDetails(owner, repo);
}
}
但是出现错误:
java.lang.IllegalArgumentException: Could not locate ResponseBody converter for class model.Data.
对于 maven 依赖:
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-gson</artifactId>
<version><latest-version></version>
</dependency>
对于代码添加一个 ConverterFactory:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
这应该可以做到。
根据官网的信息,我添加了最新的depedency,开始开发。
首先我用我感兴趣的数据创建了模型:
public class Data{
String parametr1;
//geters and setters ommited
}
第二步是添加服务:
public interface GitHubService {
@GET("/repos/{owner}/{repo}")
Call<Data> repoInfos(@Path("user") String owner, @Path("repo") String repo);
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").build();
}
第三个是添加实现:
@Service
public class GitHubServiceImpl implements GitHubService {
final GitHubService gitHubService = GitHubService.retrofit.create(GitHubService.class);
@Override
public Call<DetailDto> repoDetails(String owner, String repo) {
return gitHubService.repoDetails(owner, repo);
}
}
但是出现错误:
java.lang.IllegalArgumentException: Could not locate ResponseBody converter for class model.Data.
对于 maven 依赖:
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-gson</artifactId>
<version><latest-version></version>
</dependency>
对于代码添加一个 ConverterFactory:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
这应该可以做到。