Retrofit示例 ,Retrofit 注解学习

本文详细介绍了如何使用Retrofit2.1.0进行HTTPGET请求,利用Gson进行JSON数据解析,并展示了两种方式:一种是手动处理ResponseBody,另一种是通过GsonConverterFactory自动转换。同时,还介绍了Retrofit与其他库(如RxJava)的集成,以及各种请求参数注解的用法。
摘要由CSDN通过智能技术生成

 使用之前加入依赖:

compile 'com.squareup.retrofit2:retrofit:2.1.0'

定义接口

public interface GithubService {

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

}

这里我们使用http中的get 方法获取users这个接口下,当前user的具体信息,参数为当前user名。返回内容为Http请求的ResponseBody。

Retrofit 返回ResponseBody

private void SimpleRetrofit() {
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        Retrofit.Builder builder = new Retrofit.Builder()
                .baseUrl(BASE_URL);
        Retrofit retrofit = builder.client(httpClient.build()).build();
        GithubService simpleService = retrofit.create(GithubService.class);
        Call<ResponseBody> call = simpleService.getUserString(name);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                loading.dismiss();
                try {
                    String result = response.body().string();
                    Gson gson = new Gson();
                    GithubUserBean bean = gson.fromJson(result, GithubUserBean.class);
                    setUserView(bean);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                loading.dismiss();
            }
        });
    }

private void setUserView(GithubUserBean user) {
        if (user != null) {
            viewShell.removeAllViews();
            View view = LayoutInflater.from(mContext).inflate(R.layout.user_item_layout, null);
            TextView title = (TextView) view.findViewById(R.id.title);
            TextView id = (TextView) view.findViewById(R.id.userId);
            TextView creteaTime = (TextView) view.findViewById(R.id.createTime);
            TextView updateTime = (TextView) view.findViewById(R.id.updateTime);
            TextView bio = (TextView) view.findViewById(R.id.bio);
            ImageView avatar = (ImageView) view.findViewById(R.id.avatar);

            title.setText("Name: " + user.getLogin());
            bio.setText("Bio: " + user.getBio());
            id.setText("Id: " + String.valueOf(user.getId()));
            creteaTime.setText("createTime: " + user.getCreated_at());
            updateTime.setText("updateTime: " + user.getUpdated_at());
            Glide.with(mContext).load(user.getAvatar_url()).into(avatar);

            viewShell.addView(view);
        } else {
            Toast.makeText(mContext, "result is null", Toast.LENGTH_SHORT).show();
        }
    }

GitHubUserBean 为网络请求结果json数据所对应的实体类。

通过这段代码,我们在最终的回调方法里可以友好的处理请求结果,失败时onFailure方法执行。成功时,onResponse方法执行,我们在这里用Gson解析返回的数据,并进行UI更新操作(setUserView(bean)),

这里我们这样做有些啰嗦,Gson转换的方式都是类似,唯一不同的只是每次网络请求结果对应的实体类;因此我们可以借助强大的Retrofit帮助我们完成Gson转换的步骤。当然,如果在你所在的开发环境中,接口返回的并不是json格式的数据,也没有问题的。

Retrofit官网对可转换类型给出的介绍。有这么多种,当然了如果你们家服务器返回的数据格式比较神奇,你也可以自定义转换类。

好了,言归正传,这里还是以Json 格式数据为例。

添加依赖:

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

注意这里converter-gson 的版本号,要和之前Retrofit的版本号保持一致。

我们重新定义接口:

public interface GithubService {
    @GET("users/{user}")
    Call<GithubUserBean> getUser(@Path("user") String user);

}

这里我们用GithubUserBean取代ResponseBody,直接将其作为返回类型。

Retrofit 返回对象

private void LazyRetrofit() {
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        Retrofit.Builder builder = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create());
        Retrofit retrofit = builder.client(httpClient.build()).build();
        GithubService service = retrofit.create(GithubService.class);
        Call<GithubUserBean> call = service.getUser(name);
        call.enqueue(new Callback<GithubUserBean>() {
            @Override
            public void onResponse(Call<GithubUserBean> call, Response<GithubUserBean> response) {
                GithubUserBean bean = response.body();
                setUserView(bean);
                loading.dismiss();
            }

            @Override
            public void onFailure(Call<GithubUserBean> call, Throwable t) {
                loading.dismiss();
            }
        });
    }

这里的实现方式和上面基本相似,只是多了一行

.addConverterFactory(GsonConverterFactory.create());

 这样,我们在onResponse中获得就是对象,不再需要做额外的转换工作,可以直接使用。

Retrofit 注解学习

这里我们就看看将RxJava 和我们之前的内容结合在一起会有怎样的效果。

@Path : 请求的参数值直接跟在URL后面时,用@Path配置
@Query: 表示查询参数,以?key1=value1&key2=value2的形式跟在请求域名后面时使用
@QueryMap :以map的方式直接传入多个键值对的查询参数
@Field: 多用于post请求中表单字段,每个@Field后面,对应一对键值对。
@FieldMap :以map的方式传入多个键值对,作为body参数
@Body: 相当于多个@Field,以对象的形式提交

1、GET请求:

(1)@Query

仅带查询参数:http://192.168.0.1/weather?city=北京

   @GET("weather")
   Observable<WeatherEntity> getWeather(@Query("city") String city);

(2)@Path

请求参数直接跟在请求路径下:http://192.168.0.1/weather/北京

@GET("weather/{city_name}")
Observable<Object> getWeather(@Path("city_name") String city_name);

(3)@Path和@QueryMap结合

此种情形用得比较少:http://192.168.0.1/weather/北京?user_id=1&user_name=jojo

@GET("weather/{city_name}")
Observable<Object> getWeather(@Path("city_name")String city_name, @QueryMap Map<String, String> queryParams);
    HashMap<String, String> queryParams= new HashMap<>();
    hashMap.put("user_id","1");
    hashMap.put("user_name","jojo");

2、POST请求:

(1)情形一: http://192.168.0.1/comment
body参数:{"comment_id":"1","content":"我是评论","user_id":"1001"}

@Filed 方式处理

    @FormUrlEncoded //使用@Field时记得添加@FormUrlEncoded
    @POST("comment")
    void doComments(@Field("comment_id")String comment_id, @Field("content")String content, @Field("user_id") String user_id);

@FieldMap 方式处理

 @FormUrlEncoded
 @POST("comment")
 void doComments(@FieldMap Map<String, String> paramsMap );

通过键值对,以表单的形式提交:

  HashMap<String, String> hashMap = new HashMap<>();
  hashMap.put("comment_id","1");
  hashMap.put("content","我是评论");
  hashMap.put("user_id","1001");

@Body方式处理

  @POST("comment")
  void doComments(@Body Object reqBean);
  @POST("comment")
  void doComments(@Body List<Object> requestList);

(2)情形二:Retrofit文件上传: http://192.168.0.1/upload/

  /**
     * 文件上传
     */
    @POST("upload/")
    Observable<Object> uploadFile(@Body RequestBody requestBody);

只不过文件上传传入的是RequestBody类型,下面是构建RequestBody的方式:

  File file = new File(mFilePath); //mImagePath为上传的文件绝对路径
        //构建body
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file))
                .build();

3、PUT请求:

(1)情形一:http://192.168.0.1/comment/88

  @PUT("comment/{comment_id}")
    void comment(@Path("comment_id") String comment_id);

(2)情形二:http://192.168.0.1/comment/88?user_id=1001

    @PUT("comment/{comment_id}")
    void comment(@Path("comment_id") String comment_id @Query("user_id") String user_id);

 (3)情形三:http://192.168.0.1/comment/88?user_id=1001

加body参数:{"content":"我是评论","type":"1"}

此类请求的应用场景:适合于body中需要传入多个请求参数,这样可以将多个请求的参数字段封装到一个实体中,这样就不用写多个@Filed了。

public class RequestBean {
    public String content;
    public String type;
    //实际中可能还有多个请求字段
}
RequestBean  requestBean = new RequestBean();
    requestBean .content = "我是评论";
    requestBean .type = "1";
T("comment/{comment_id}")
    void comment(@Path("comment_id") String comment_id @Query("user_id") String user_id @Body RequestBean reqBean);

4、DELETE请求:

假如删除评论:http://192.168.0.1/comment/88

 @DELETE("comment/{comment_id}")
    void comment(@Path("comment_id") String comment_id);

其他可能的delete请求,配置方式都是类似的,这里就不多举例了。主要是要好好理解下面这些常用的请求参数注解的作用和用法。

  • 18
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Retrofit是一个基于OkHttp的RESTful API库,可以方便地调用网络接口。下面是一个简单的示例,展示如何使用Retrofit调用接口。 首先,需要在项目中添加Retrofit的依赖项。可以在build.gradle文件中添加以下代码: ``` implementation 'com.squareup.retrofit2:retrofit:2.9.0' ``` 接下来,需要定义一个接口,用于描述要调用的API。这个接口需要使用注解来描述请求的方式、URL和请求参数等信息。例如: ``` public interface MyApi { @GET("users/{userId}/repos") Call<List<Repo>> listRepos(@Path("userId") String userId); } ``` 这个接口定义了一个名为listRepos的方法,该方法使用GET请求,URL为/users/{userId}/repos,其中{userId}是一个路径参数。该方法返回一个Call对象,表示异步调用API并返回一个List<Repo>对象。 接下来,需要创建一个Retrofit实例,并使用该实例创建一个API对象。例如: ``` Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com/") .build(); MyApi myApi = retrofit.create(MyApi.class); ``` 这里创建了一个基础URL为https://api.github.com/的Retrofit实例,并使用它创建了一个MyApi对象。 最后,可以调用API方法并处理响应。例如: ``` Call<List<Repo>> call = myApi.listRepos("octocat"); call.enqueue(new Callback<List<Repo>>() { @Override public void onResponse(Call<List<Repo>> call, Response<List<Repo>> response) { List<Repo> repos = response.body(); // 处理响应数据 } @Override public void onFailure(Call<List<Repo>> call, Throwable t) { // 处理请求失败 } }); ``` 这里使用listRepos方法异步调用API,并在响应时处理返回的数据。如果请求失败,则调用onFailure方法。 这就是使用Retrofit调用接口的基本流程。通过定义API接口并使用Retrofit创建API对象,可以方便地调用网络接口并处理响应。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值