Retrofit简单使用

    //添加retrofit依赖
    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    //添加gson转换器的依赖

    compile 'com.squareup.retrofit2:converter-gson:2.3.0'


  配置服务接口

public interface ApiService {

    //注解后面是路径,,,但是这个路径比较特殊
    //https://www.zhaoapi.cn/----baseUrl ----http://163.16.11.22:8080/
    // product/getProductCatagory----相对路径----linzhiling/lingzhiling.jpg

    @GET("product/getProductCatagory")
    Call<CategaryBean> getCategary();

    //https://www.zhaoapi.cn/product/searchProducts?keywords=笔记本&page=1&source=android

    @GET("product/searchProducts")
    Call<SearchBean> getSearch(@QueryMap Map<String,String> map);

    //post传递的是表单数据
    @FormUrlEncoded
    @POST("product/searchProducts")
    Call<SearchBean> postSearch(@FieldMap Map<String,String> map);

    @FormUrlEncoded
    @POST("product/searchProducts")
    Call<SearchBean> postSearch_02(@Field("keywords") String keywords, @Field("page") String page, @Field("source") String source);

    @GET("users/{user}/repos") //{user}请求路径上的占位符
    Call<ResponseBody>  getBlog(@Path("user") String user);
    // 访问的API是:https://api.github.com/users/{user}/repos
    // 在发起请求时, {user} 会被替换为方法的第一个参数 user(被@Path注解作用)

}

CategaryBean 为返回数据的实体类

    // Unable to create converter转换器 for class com.dash.a05_retrofit.CategaryBean
    //不能够为CategaryBean创建一个转换器---response.body().string()---json字符串--Gson->CategaryBean
    //json xml jackSon --->对应着不同的转换器
    public void getCategory(View view) {

        Retrofit retrofit = new Retrofit.Builder()//构建者模式
                .baseUrl(Constant.BASE_URL)//设置baseUrl
                .addConverterFactory(GsonConverterFactory.create())//添加gson转换器
                .build();

        //需要使用retrofit创建一个网络请求的接口
        ApiService apiService = retrofit.create(ApiService.class);

        Call<CategaryBean> call = apiService.getCategary();

        call.enqueue(new Callback<CategaryBean>() {
            @Override
            public void onResponse(Call<CategaryBean> call, Response<CategaryBean> response) {
                if (response.isSuccessful()) {
                    CategaryBean categaryBean = response.body();

                    //主线程还是子线程????---主线程,,retrofit自动完成了线程的切换
                    text_view.setText(categaryBean.getMsg());
                }
            }

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

            }
        });

    }

    public void getCategory_02(View view) {

        //这部分代码其实是写在model里面的

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constant.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        ApiService apiService = retrofit.create(ApiService.class);

        Map<String, String> params = new HashMap<>();
        params.put("keywords","笔记本");
        params.put("page","1");
        params.put("source","android");

        //Call<SearchBean> call = apiService.getSearch(params);

        //Call<SearchBean> call = apiService.postSearch(params);

        Call<SearchBean> call = apiService.postSearch_02("笔记本", "1", "android");

        call.enqueue(new Callback<SearchBean>() {
            @Override
            public void onResponse(Call<SearchBean> call, Response<SearchBean> response) {
                text_view.setText(response.body().getData().get(0).getTitle());
            }

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

            }
        });

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Retrofit 是一个开源的 Android 网络请求库,它简化了与 RESTful API 进行交互的过程。你可以使用 Retrofit 来发送网络请求并处理服务器返回的数据。 下面是使用 Retrofit 的一般步骤: 1. 添加 Retrofit 依赖:在你的项目的 build.gradle 文件添加以下依赖: ```groovy implementation 'com.squareup.retrofit2:retrofit:2.x.x' ``` 2. 创建 API 接口:定义一个接口来描述你要访问的 API 端点和请求方法。例如: ```java public interface ApiService { @GET("users/{username}") Call<User> getUser(@Path("username") String username); } ``` 3. 创建 Retrofit 实例:使用 Retrofit.Builder 类构建一个 Retrofit 实例,配置基本的 URL 和转换器等。 ```java Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); ``` 4. 创建 API 服务:使用 Retrofit 实例创建一个实现了你的 API 接口的服务。 ```java ApiService apiService = retrofit.create(ApiService.class); ``` 5. 发送网络请求:通过调用 API 服务的方法发送网络请求,并处理返回的结果。 ```java Call<User> call = apiService.getUser("CSDN"); call.enqueue(new Callback<User>() { @Override public void onResponse(Call<User> call, Response<User> response) { if (response.isSuccessful()) { User user = response.body(); // 处理返回的用户数据 } else { // 处理请求失败情况 } } @Override public void onFailure(Call<User> call, Throwable t) { // 处理请求失败情况 } }); ``` 这只是一个简单的示例,你可以根据自己的需求进行更复杂的网络请求和数据处理。希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值