使用之前加入依赖:
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请求,配置方式都是类似的,这里就不多举例了。主要是要好好理解下面这些常用的请求参数注解的作用和用法。