Retrofit学习(一)集成-简单get请求​​​​​​​


   Retrofit学习(一)集成-简单get请求

集成

githubhttps://github.com/square/retrofit

在studio在添加依赖

 //添加retrofit-会自动下载okhttp
compile 'com.squareup.retrofit2:retrofit:2.1.0'
    //添加retrofit gson转换会自动下载gson
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    //添加返回的字符串支付
compile 'com.squareup.retrofit2:converter-scalars:2.1.0'

可以用其它的retrofit2支付的替代见连接
转换可以在API处找到
http://square.github.io/retrofit/#api-declaration
右侧点击Retrofit Configuration版本与retrofit2保持一直即可

Gson: com.squareup.retrofit2:converter-gson
Jackson: com.squareup.retrofit2:converter-jackson
Moshi: com.squareup.retrofit2:converter-moshi
Protobuf: com.squareup.retrofit2:converter-protobuf
Wire: com.squareup.retrofit2:converter-wire
Simple XML: com.squareup.retrofit2:converter-simplexml
Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars

第一个get请求

添加网络权限

<uses-permission android:name="android.permission.INTERNET"/>

建立接口

public interface GitHubService {

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

简单说明一下
@GET表示为get请求,还会有@POST
@PATH 表示后面的参数要添加到@GET后面对应的{user}中,{user}相当于一个占位符
学习spring MVC都知道这种做学法把请求参数添加到请求路径中去,

@Query就是我们的请求的键值对的设置
@QueryMap 和@Query相似 就是个传个map集合,也是键值对

开始请求

界面就一个按键点击可以请求

结果

OK  [{"id":18221276,"name":"git-consortium","full_name":"octocat/git-consortium","owner":{"login":"octocat","id":583231,"avatar_url":"https://avatars.githubusercontent.com/u/583231?v=3","gravatar_id":"","url":"https://api.github.com/users/octocat","html_url":"https://github.com/octocat","followers_url":"https://api.github.com/users/octocat/followers","following_url":"https://api.github.com/users/octocat/following{/other_user}","gists_url":"https://api.github.com/users/octocat/gists{/gist_id}","starred_url":"https://api.github.com/users/octocat/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/octocat/subscriptions","organizations_url":"https://api.github.com/users/octocat/orgs","repos_url":"https://api.github.com/users/octocat/repos","events_url":"https://api.github.com/users/octocat/events{/privacy}","received_events_url":"https://api.github.com/users/octocat/received_events","type":"User","site_admin":false},"private":false,"html_url":"https://github.com/octocat/git-consortium","description":"This repo is for demonstration purposes only.","fork":false,"url":"https://api.github.com/repos/octocat/git-consortium","forks_url":"https://api.github.com/repos/octocat/git-consortium/forks","keys_url":"https://api.github.com/repos/octocat/git-consortium/keys{/key_id}","collaborators_url":"https://api.github.com/repos/octocat/git-consortium/collaborators{/collaborator}","teams_url":"https://api.github.com/repos/octocat/git-consortium/teams","hooks_url":"https://api.github.com/repos/octocat/git-consortium/hooks","issue_events_url":"https://api.github.com/repos/octocat/git-consortium/issues/events{/number}","events_url":"https://api.github.com/repos/octocat/git-consortium/events","assignees_url":"https://api.github.com/repos/octocat/git-consortium/assignees{/user}","branches_url":"https://api.github.com/repos/octocat/git-consortium/branches{/branch}","tags_url":"https://api.github.com/repos/octocat/git-consortium/tags","blobs_url":"https://api.github.com/repos/octocat/git-consortium/git/blobs{/sha}","git_tags_url":"https://api.github.com/repos/octocat/git-consortium/git/tags{/sha}","git_refs_url":"https://api.github.com/repos/octocat/git-consortium/git/refs{/sha}","trees_url":"https://api.github.com/repos/octocat/git-consortium/git/trees{/sha}","statuses_url":"https://api.github.com/repos/octocat/git-consortium/statuses/{sha}","languages_url":"https://api.github.com/repos/octocat/git-consortium/languages","stargazers_url":"https://api.github.com/repos/octocat/git-consortium/stargazers","contributors_url":"https://api.github.com/repos/octocat/git-consortium/contributors","subscribers_url":"https://api.github.com/repos/octocat/git-consortium/subscribers","subscription_url":"https://api.github.com/repos/octocat/git-consortium/subscription","commits_url":"https://api.github.com/repos/octocat/git-consortium/commits{/sha}","git_commits_url":"https://api.github.com/repos/octocat/git-consortium/git/commits{/sha}","comments_url":"https://api.github.com/repos/octocat/git-consortium/comments{/number}","issue_comment_url":"https://api.github.com/repos/octocat/git-consortium/issues/comments{/number}","contents_url":"https://api.github.com/repos/octocat/git-consortium/contents/{+path}","compare_url":"https://api.github.com/repos/octocat/git-consortium/compare/{base}...{head}","merges_url":"https://api.github.com/repos/octocat/git-consortium/merges","archive_url":"https://api.github.com/repos/octocat/git-consortium/{archive_format}{/ref}","downloads_url":"https://api.github.com/repos/octocat/git-consortium/downloads","issues_url":"https://api.github.com/repos/octocat/git-consortium/issues{/number}","pulls_url":"https://api.github.com/repos/octocat/git-consortium/pulls{/number}","milestones_url":"https://api.github.com/repos/octocat/git-consortium/milestones{/number}","notifications_url":"https://api.github.com/repos/octocat/git-consortium/notifications{?since,all,participating}","labels_url":"https://api.github.com/repos/octocat/git-consortium/labels{/name}","releases_url":"https://api.github.com

这样一个网络请求就完成了

把返回字符串返回实体类使用Gson

public class Repo {

    public int id;
    public String name;
    public String full_name;
    public OwnerEntity owner;
    @SerializedName("private")
    public boolean privateX;
    public String  html_url;
    public Object  description;
    public boolean fork;
    public String  url;
    public String  forks_url;
    public String  keys_url;
    public String  collaborators_url;
    public String  teams_url;
    public String  hooks_url;
    public String  issue_events_url;
    public String  events_url;
    public String  assignees_url;
    public String  branches_url;
    public String  tags_url;
    public String  blobs_url;
    public String  git_tags_url;
    public String  git_refs_url;
    public String  trees_url;
    public String  statuses_url;
    public String  languages_url;
    public String  stargazers_url;
    public String  contributors_url;
    public String  subscribers_url;
    public String  subscription_url;
    public String  commits_url;
    public String  git_commits_url;
    public String  comments_url;
    public String  issue_comment_url;
    public String  contents_url;
    public String  compare_url;
    public String  merges_url;
    public String  archive_url;
    public String  downloads_url;
    public String  issues_url;
    public String  pulls_url;
    public String  milestones_url;
    public String  notifications_url;
    public String  labels_url;
    public String  releases_url;
    public String  deployments_url;
    public String  created_at;
    public String  updated_at;
    public String  pushed_at;
    public String  git_url;
    public String  ssh_url;
    public String  clone_url;
    public String  svn_url;
    public Object  homepage;
    public int     size;
    public int     stargazers_count;
    public int     watchers_count;
    public String  language;
    public boolean has_issues;
    public boolean has_downloads;
    public boolean has_wiki;
    public boolean has_pages;
    public int     forks_count;
    public Object  mirror_url;
    public int     open_issues_count;
    public int     forks;
    public int     open_issues;
    public int     watchers;
    public String  default_branch;

    public static class OwnerEntity {
        public String  login;
        public int     id;
        public String  avatar_url;
        public String  gravatar_id;
        public String  url;
        public String  html_url;
        public String  followers_url;
        public String  following_url;
        public String  gists_url;
        public String  starred_url;
        public String  subscriptions_url;
        public String  organizations_url;
        public String  repos_url;
        public String  events_url;
        public String  received_events_url;
        public String  type;
        public boolean site_admin;

    }

}

记得添加toString方法方法查看

  • 更改接口返回值
public interface GitHubService {

    @GET("users/{user}/repos")
    Call<List<Repo>> listRepos(@Path("user") String user);
}
  • 再次请求
  •  

        //建立retrofit对象
        Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/")
                //添加返回字符串的支持--不知道返回的是什么,添加字符串支持
                .addConverterFactory(ScalarsConverterFactory.create())
                //添加GSON转换支持
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        //获取接口
        GitHubService service = retrofit.create(GitHubService.class);

        //调用方法-返回 回调更换为对象
        Call<List<Repo>> call = service.listRepos("octocat");

        //异步调用
        call.enqueue(new Callback<List<Repo>>() {
            @Override
            public void onResponse(Call<List<Repo>> call, Response<List<Repo>> response) {

                L.d("vivi",response.message()+"  "+response.body());
                mTvResult.setText(response.message()+" \n结果: "+response.body().toString());
                Toast.makeText(FirstActivity.this, "结果:\n "+response.body().toString(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(Call<List<Repo>> call, Throwable t) {

                t.printStackTrace();
                mTvResult.setText(t.getMessage());

            }
        });
    }
  • 简单封装
public class RetrofitWrapper {
    //单例
    private static RetrofitWrapper INSTANCE;
    // Retrofit 对象
    private Retrofit mRetrofit;

    private RetrofitWrapper(){
        mRetrofit = new Retrofit.Builder()
                .baseUrl(Constant.BASE_URL)  //添加baseurl
                .addConverterFactory(ScalarsConverterFactory.create()) //添加返回为字符串的支持
                .addConverterFactory(GsonConverterFactory.create()) //create中可以传入其它json对象,默认Gson
                .build();
    }
    public static RetrofitWrapper getInstance() {

        if(INSTANCE == null) {
            synchronized(RetrofitWrapper.class) {
                if(INSTANCE == null) {
                    INSTANCE = new RetrofitWrapper();
                }
            }
        }

        return INSTANCE;
    }

    /**
     * 转换为对象的Service
     * @param service
     * @param <T>
     * @return 传入的类型
     */
    public <T> T create(Class<T> service){
        return mRetrofit.create(service);
    }
}

  • 使用

        Call<List<Repo>> call = RetrofitWrapper.getInstance().create(GitHubService.class).listRepos("octocat");

        call.enqueue(new Callback<List<Repo>>() {
            @Override
            public void onResponse(Call<List<Repo>> call, Response<List<Repo>> response) {
                // ...do something
            }

            @Override
            public void onFailure(Call<List<Repo>> call, Throwable t) {
                  // ...do something

            }
        });

这样用着方便很多

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
智慧校园整体解决方案是响应国家教育信息化政策,结合教育改革和技术创新的产物。该方案以物联网、大数据、人工智能和移动互联技术为基础,旨在打造一个安全、高效、互动且环保的教育环境。方案强调从数字化校园向智慧校园的转变,通过自动数据采集、智能分析和按需服务,实现校园业务的智能化管理。 方案的总体设计原则包括应用至上、分层设计和互联互通,确保系统能够满足不同用户角色的需求,并实现数据和资源的整合与共享。框架设计涵盖了校园安全、管理、教学、环境等多个方面,构建了一个全面的校园应用生态系统。这包括智慧安全系统、校园身份识别、智能排课及选课系统、智慧学习系统、精品录播教室方案等,以支持个性化学习和教学评估。 建设内容突出了智慧安全和智慧管理的重要性。智慧安全管理通过分布式录播系统和紧急预案一键启动功能,增强校园安全预警和事件响应能力。智慧管理系统则利用物联网技术,实现人员和设备的智能管理,提高校园运营效率。 智慧教学部分,方案提供了智慧学习系统和精品录播教室方案,支持专业级学习硬件和智能化网络管理,促进个性化学习和教学资源的高效利用。同时,教学质量评估中心和资源应用平台的建设,旨在提升教学评估的科学性和教育资源的共享性。 智慧环境建设则侧重于基于物联网的设备管理,通过智慧教室管理系统实现教室环境的智能控制和能效管理,打造绿色、节能的校园环境。电子班牌和校园信息发布系统的建设,将作为智慧校园的核心和入口,提供教务、一卡通、图书馆等系统的集成信息。 总体而言,智慧校园整体解决方案通过集成先进技术,不仅提升了校园的信息化水平,而且优化了教学和管理流程,为学生、教师和家长提供了更加便捷、个性化的教育体验。
Spring Boot 可以与 Retrofit2 集成,以便在应用程序中使用 Retrofit2 进行网络请求。 首先,需要在项目的构建文件中添加 Retrofit2 和其所需的依赖项。通常,可以在 Maven 或 Gradle 文件中添加以下依赖项: Maven: ```xml <dependencies> ... <dependency> <groupId>com.squareup.retrofit2</groupId> <artifactId>retrofit</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>com.squareup.retrofit2</groupId> <artifactId>retrofit-converters</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>com.squareup.retrofit2</groupId> <artifactId>converter-gson</artifactId> <version>2.9.0</version> </dependency> ... </dependencies> ``` Gradle: ```groovy dependencies { ... implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.9.0' ... } ``` 接下来,创建一个 Retrofit 的配置类,用于创建 Retrofit 实例。在该类中,可以设置 Retrofit 的基本配置,如 Base URL、Converter 等。以下是一个简单的示例: ```java @Configuration public class RetrofitConfig { @Value("${api.baseurl}") private String baseUrl; @Bean public Retrofit retrofit() { return new Retrofit.Builder() .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create()) .build(); } } ``` 上述示例中,`api.baseurl` 是一个配置属性,用于指定基本的 API URL。 然后,可以创建一个 Retrofit 的服务接口,定义需要访问的 API 接口。例如: ```java public interface MyApiService { @GET("/users/{id}") Call<User> getUser(@Path("id") String id); } ``` 在上述示例中,`User` 是一个自定义的数据模型类。 最后,在需要使用 Retrofit2 的地方,可以通过依赖注入的方式获取 Retrofit 实例,并使用它创建服务接口的实例。例如: ```java @Service public class MyService { private final MyApiService myApiService; @Autowired public MyService(Retrofit retrofit) { this.myApiService = retrofit.create(MyApiService.class); } public User getUser(String id) { Call<User> call = myApiService.getUser(id); Response<User> response = call.execute(); if (response.isSuccessful()) { return response.body(); } else { // 处理请求失败的情况 return null; } } } ``` 在上述示例中,通过 Retrofit 的 `create()` 方法创建了 `MyApiService` 的实例,并使用该实例进行网络请求。 需要注意的是,上述示例中的代码仅供参考,具体的实现可能会根据项目的需求和架构进行调整。 希望能帮到你!如果还有其他问题,请继续提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值