Retrofit闲聊,初学者可以参考

一.先看一个完整的例子:

package com.github.ikidou;

import java.io.IOException;

import okhttp3.ResponseBody;

import retrofit2.Call;

import retrofit2.Callback;

import retrofit2.Response;

import retrofit2.Retrofit;

import retrofit2.http.GET;

import retrofit2.http.Path;

/**

* [Retrofit入门]源码

*/

public class Example01{

public interface BlogService{

@GET("blog/{id}")//这里的{id} 表示是一个变量

CallgetBlog(/** 这里的id表示的是上面的{id}*/@Path("id")intid);

    }

public static void main(String[]args)throws IOException{

Retrofit retrofit=new Retrofit.Builder()

.baseUrl("http://localhost:4567/")

                .build();

BlogService service = retrofit.create(BlogService.class);

Call call=service.getBlog(2);

//用法和OkHttp的call如出一辙

//不同的是如果是Android系统回调方法执行在主线程

call.enqueue(new Callback() {

@Override

public void onResponse(

Call call , Response response) {

try{

System.out.println(response.body().string());

}catch(IOExceptione) {

e.printStackTrace();

                }

            }

@Override

public void onFailure(Callcall,Throwablet) {

t.printStackTrace();

            }

        });

    }

}

二.进行拆解分析:

public interface BlogService{

@GET("blog/{id}")//这里的{id} 表示是一个变量

CallgetBlog(/** 这里的id表示的是上面的{id}*/@Path("id")intid);

    }

这个接口算是retrofit里面的重要部位.

@GET("blog/{id}")代表注解,不清楚的可以google或者百度了解一下.

{id}在@GET注解中,指CallgetBlog(@Path("id")int id);这个函数里面的id,后期调用函数CallgetBlog将会传入参数id.

可以使用方法中的替换块和参数动态更新请求URL

读懂下面这几句话:

Use annotations to describe the HTTP request:

URL parameter replacement and query parameter support

Object conversion to request body (e.g., JSON, protocol buffers)

Multipart request body and file upload

以上就是注解相关传参方式解释.

如果自学能力强,英文基础好的,可以直接在官网学习

官网学习链接

1.REQUEST METHOD(请求方法)

Every method must have an HTTP annotation that provides the request method and relative URL. There are five built-in annotations: GET, POST, PUT, DELETE, and HEAD. The relative URL of the resource is specified in the annotation.

Query parameters(查询参数) can also be added.

比如从服务器上获取新闻信息等.

@GET("group/{id}/users")Call> groupList(@Path("id") int groupId, @Query("sort") String sort);

//@Query将在url地址中追加类似“page=1”的字符串,形成提交给服务端的请求参数

2.对于复杂的查询参数组合,可以使用MAP。

@GET("group/{id}/users")

Call<List<User>>groupList(@Path("id") int groupId , @QueryMap Map options);

@QueryMap Map options这个并不是要像@Path一样拼接进参数.

3.REQUEST BODY(请求体形式)

An object can be specified for use as an HTTP request body with the @Body annotation.

@POST("users/new")

Call<User>createUser(@Body User user);

4. FORM ENCODED AND MULTIPART(上传信息)

Methods can also be declared to send form-encoded and multipart data.Form-encoded data is sent when @FormUrlEncoded is present on the method. Each key-value pair is annotated with @Fieldcontaining the name and the object providing the value.

@FormUrlEncoded

@POST("user/edit")

Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);

Multipart requests are used when @Multipart is present on the method. Parts are declared using the @Part annotation.

@Multipart

@PUT("user/photo")

Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);

5.HEADER MANIPULATION

注意,头文件不会覆盖彼此。所有具有相同名称的头将包含在请求中(如果不清楚的可以先大概学习HTTP请求相关知识)

You can set static headers for a method using the @Headers annotation.

@Headers("Cache-Control: max-age=640000")

@GET("widget/list")

Call<List<Widget>> widgetList();

@Headers({

    "Accept: application/vnd.github.v3.full+json",

    "User-Agent: Retrofit-Sample-App"

})

@GET("users/{username}")

Call<User> getUser(@Path("username") String username);                                           

A request Header can be updated dynamically using the @Header annotation. A corresponding parameter must be provided to the @Header. If the value is null, the header will be omitted. Otherwise, toString will be called on the value, and the result used.

@GET("user")

Call<User> getUser(@Header("Authorization") String authorization)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,303评论 19 139
  • 一、简介 Retrofit是Square公司开发的一款针对Android网络请求的框架,Retrofit2底层基于...
    Devil不加V阅读 658评论 0 0
  • 你见,或者不见我 我就在那里 不悲不喜 你念,或者不念我 情就在那里 不来不去 你爱,或者不爱我 爱就在那里 不增不减
    逍遥_9353阅读 225评论 0 3
  • 一直都想减肥,每一次努力聚集起的勇气却都被惰性打败。 前段时间和朋友外出,闲来无聊,朝四周看,偶然看见一位帅...
    梁上_阅读 261评论 0 1
  • 第二十七 不哭死神 第二天。 风云会。 风云殿。 这是一座年久失修十分阴森恐怖的大殿。 殿里灰尘寸厚,蛛网密布,老...
    狼神2019阅读 390评论 4 12

友情链接更多精彩内容