转自:http://ranseti.top/article/retrofit_github_api_demo
直接上代码
import com.google.gson.Gson;
import java.io.IOException;
import java.util.List;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Path;
/**
* Created by qy on 2018/1/29.
*/
public class RetrfitTest {
public static void main(String[] args) {
try {
retrfitTest();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void retrfitTest() throws IOException {
//创建一个非常简单的指向GitHub API的REST适配器。
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
//创建我们的GitHub API接口的一个实例。
GitHub github = retrofit.create(GitHub.class);
//创建一个调用实例来查找Retrofit贡献者。
Call<List<Contributor>> call = github.contributors("square", "retrofit");
//获取并打印库的贡献者列表。
Response response = call.execute();
System.out.println(response.code() + "\n"
+ response.toString() + "\n"
+ new Gson().toJson(response.body()));
}
public static class Contributor {
public final String login;
public final int contributions;
public Contributor(String login, int contributions) {
this.login = login;
this.contributions = contributions;
}
}
//https://api.github.com/repos/square/retrofit/contributors
public static final String API_URL = "https://api.github.com";
public interface GitHub {
@GET("/repos/{owner}/{repo}/contributors")
Call<List<Contributor>> contributors(
@Path("owner") String owner,
@Path("repo") String repo);
}
}
点击main()方法运行结果为
200
Response{protocol=http/1.1, code=200, message=OK, url=https://api.github.com/repos/square/retrofit/contributors}
[{"login":"JakeWharton","contributions":871},{"login":"swankjesse","contributions":211},{"login":"pforhan","contributions":48},{"login":"eburke","contributions":36},{"login":"dnkoutso","contributions":26},{"login":"edenman","contributions":24},{"login":"loganj","contributions":17},{"login":"NightlyNexus","contributions":14},{"login":"rcdickerson","contributions":14},{"login":"rjrjr","contributions":13},{"login":"kryali","contributions":9},{"login":"adriancole","contributions":8},{"login":"holmes","contributions":7},{"login":"swanson","contributions":7},{"login":"JayNewstrom","contributions":6},{"login":"crazybob","contributions":6},{"login":"Jawnnypoo","contributions":6},{"login":"danrice-square","contributions":5},{"login":"Turbo87","contributions":5},{"login":"ransombriggs","contributions":4},{"login":"vanniktech","contributions":4},{"login":"naturalwarren","contributions":4},{"login":"guptasourabh04","contributions":4},{"login":"artem-zinnatullin","contributions":3},{"login":"codebutler","contributions":3},{"login":"icastell","contributions":3},{"login":"jjNford","contributions":3},{"login":"f2prateek","contributions":3},{"login":"koalahamlet","contributions":3},{"login":"alexgyori","contributions":2}]
网友评论