Android十大主流开源框架使用教程---Retrofit使用教程

首先第一步还是添加依赖

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

准备开始get请求

创建一个接口,用来存放请求的方法

@get是选择请求的方式,后面的内容为追加的URL

需要添加请求头的可以加一个@headers("")

public interface IRetrofit {
    @GET(".../login")
    Call getinfo();
        }

如果是带参数的,那么就在getinfo中添加:需要几个就添加几个


Call getinfo(@Query("name") String name);

开始网络请求

Retrofit retrofit=new Retrofit.Builder()
        .baseUrl("url")
        .addConverterFactory(GsonConverterFactory.create())
        .build();
IRetrofit iRetrofit=retrofit.create(IRetrofit.class);
Call call=iRetrofit.getinfo();
call.enqueue(new retrofit2.Callback() {
    @Override
    public void onResponse(retrofit2.Call call, retrofit2.Response response) {

    }

    @Override
    public void onFailure(retrofit2.Call call, Throwable t) {

    }
});

上传文件

接口里面新增一个请求

@Multipart
@POST("upload")
Call upload(@Part MultipartBody.Part file);
File file=new File("");
Retrofit retrofit=new Retrofit.Builder()
        .baseUrl("url")
        .addConverterFactory(GsonConverterFactory.create())
        .build();
RequestBody requestBody=RequestBody.create(MediaType.parse("multipart/form-data"),file);
MultipartBody.Part body=MultipartBody.Part.createFormData("file",file.getName(),requestBody);
//执行请求

IRetrofit iRetrofit=retrofit.create(IRetrofit.class);
Call call=iRetrofit.upload(body);
call.enqueue(new Callback() {
    @Override
    public void onResponse(Call call, Response response) {

    }

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

    }
});

你可能感兴趣的:(Android十大主流开源框架使用教程---Retrofit使用教程)