参考自:https://blog.csdn.net/carson_ho/article/details/73732076
一、初识
1、 基于OkHttp
- 真正的请求是用OkHttp完成的,Retrofit只是封装接口
2、 通过注解的方式配置参数
- (1)网络请求方法类
- (2)标记类
- (3)网络请求参数类
-
@Field & @FieldMap
- 作用:发送 Post请求 时提交请求的表单字段
- 具体使用:与
FormUrlEncoded
(表示请求体是一个Form表单)注解配合使用
//定义请求接口 public interface GetRequest_Interface { /** *表明是一个表单格式的请求(Content-Type:application/x-www-form-urlencoded) * <code>Field("username")</code> 表示将后面的 <code>String name</code> 中name的取值作为 username 的值 */ @POST("/form") @FormUrlEncoded Call<ResponseBody> testFormUrlEncoded1(@Field("username") String name, @Field("age") int age); /** * Map的key作为表单的键 */ @POST("/form") @FormUrlEncoded Call<ResponseBody> testFormUrlEncoded2(@FieldMap Map<String, Object> map); }
//配置参数 // @Field Call<ResponseBody> call1 = service.testFormUrlEncoded1("Carson", 24); // @FieldMap // 实现的效果与上面相同,但要传入Map Map<String, Object> map = new HashMap<>(); map.put("username", "Carson"); map.put("age", 24); Call<ResponseBody> call2 = service.testFormUrlEncoded2(map);
-
@Part & @PartMap
- 作用:发送 Post请求 时提交请求的表单字段
- 与@Field的区别:功能相同,但携带的参数类型更加丰富,包括数据流,所以适用于 有文件上传 的场景
- 具体使用:与
@Multipart
(表示请求体是一个支持文件上传的Form表单)注解配合使用
//定义请求接口 public interface GetRequest_Interface { /** * {@link Part} 后面支持三种类型,{@link RequestBody}、{@link okhttp3.MultipartBody.Part} 、任意类型 * 除 {@link okhttp3.MultipartBody.Part} 以外,其它类型都必须带上表单字段({@link okhttp3.MultipartBody.Part} 中已经包含了表单字段的信息), */ @POST("/form") @Multipart Call<ResponseBody> testFileUpload1(@Part("name") RequestBody name, @Part("age") RequestBody age, @Part MultipartBody.Part file); /** * PartMap 注解支持一个Map作为参数,支持 {@link RequestBody } 类型, * 如果有其它的类型,会被{@link retrofit2.Converter}转换,如后面会介绍的 使用{@link com.google.gson.Gson} 的 {@link retrofit2.converter.gson.GsonRequestBodyConverter} * 所以{@link MultipartBody.Part} 就不适用了,所以文件只能用<b> @Part MultipartBody.Part </b> */ @POST("/form") @Multipart Call<ResponseBody> testFileUpload2(@PartMap Map<String, RequestBody> args, @Part MultipartBody.Part file); @POST("/form") @Multipart Call<ResponseBody> testFileUpload3(@PartMap Map<String, RequestBody> args); }
//配置参数 MediaType textType = MediaType.parse("text/plain"); RequestBody name = RequestBody.create(textType, "Carson"); RequestBody age = RequestBody.create(textType, "24"); RequestBody file = RequestBody.create(MediaType.parse("application/octet-stream"), "这里是模拟文件的内容"); // @Part MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", "test.txt", file); Call<ResponseBody> call3 = service.testFileUpload1(name, age, filePart); ResponseBodyPrinter.printResponseBody(call3); // @PartMap // 实现和上面同样的效果 Map<String, RequestBody> fileUpload2Args = new HashMap<>(); fileUpload2Args.put("name", name); fileUpload2Args.put("age", age); //这里并不会被当成文件,因为没有文件名(包含在Content-Disposition请求头中),但上面的 filePart 有 //fileUpload2Args.put("file", file); Call<ResponseBody> call4 = service.testFileUpload2(fileUpload2Args, filePart); //单独处理文件 ResponseBodyPrinter.printResponseBody(call4);
- 作用:发送 Post请求 时提交请求的表单字段
-
@Query和@QueryMap
- 作用:用于 @GET 方法的查询参数(Query = Url 中 ‘?’ 后面的 key-value)
- 具体使用:
@GET("/") Call<String> cate(@Query("cate") String cate); } // 其使用方式同 @Field与@FieldMap,这里不作过多描述
-
@Path
- 作用:URL地址的缺省值
- 具体使用:
public interface GetRequest_Interface { @GET("users/{user}/repos") Call<ResponseBody> getBlog(@Path("user") String user ); // 访问的API是:https://api.github.com/users/{user}/repos // 在发起请求时, {user} 会被替换为方法的第一个参数 user(被@Path注解作用) }
-
@Url
- 作用:直接传入一个请求的 URL变量 用于URL设置
- 具体使用:
public interface GetRequest_Interface { @GET Call<ResponseBody> testUrlAndQuery(@Url String url, @Query("showAll") boolean showAll); // 当有URL注解时,@GET传入的URL就可以省略 // 当GET、POST...HTTP等方法中没有设置Url时,则必须使用 {@link Url}提供 }
-
二、使用
1、添加Retrofit库的依赖
- build.gradle添加retrofit和OkHttp的依赖
dependencies {
compile 'com.squareup.retrofit2:retrofit:2.0.2'
// Retrofit库
compile 'com.squareup.okhttp3:okhttp:3.1.2'
// Okhttp库
}
- AndroidManifest打开网络权限
<uses-permission android:name="android.permission.INTERNET"/>
2、创建 接收服务器返回数据 的类
- 使用Gosn(或其他方式)定义实体类
3、创建 用于描述网络请求 的接口
- GetRequest_Interface.java
public interface GetRequest_Interface {
@GET("ajax.php?a=fy&f=auto&t=auto&w=hello%20world")
Call<Translation> getCall();
// 注解里传入 网络请求 的部分URL地址
// Retrofit把网络请求的URL分成了两部分:一部分放在Retrofit对象里,另一部分放在网络请求接口里
// 如果接口里的url是一个完整的网址,那么放在Retrofit对象里的URL可以忽略
// getCall()是接受网络请求数据的方法
}
4、创建 Retrofit 实例
5、创建 网络请求接口实例 并 配置网络请求参数
6、发送网络请求(异步 / 同步)
7、处理服务器返回的数据
- GetRequest.java
public class GetRequest extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
request();
// 使用Retrofit封装的方法
}
public void request() {
//步骤4:创建Retrofit对象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://fy.iciba.com/") // 设置 网络请求 Url
.addConverterFactory(GsonConverterFactory.create()) //设置使用Gson解析(记得加入依赖)
.build();
// 步骤5:创建 网络请求接口 的实例
GetRequest_Interface request = retrofit.create(GetRequest_Interface.class);
//对 发送请求 进行封装
Call<Translation> call = request.getCall();
//步骤6:发送网络请求(异步)
call.enqueue(new Callback<Translation>() {
//请求成功时回调
@Override
public void onResponse(Call<Translation> call, Response<Translation> response) {
// 步骤7:处理返回的数据结果
response.body().show();
}
//请求失败时回调
@Override
public void onFailure(Call<Translation> call, Throwable throwable) {
System.out.println("连接失败");
}
});
}
}