SAKA'S BLOG

Retrofit使用详解(四)

在安卓上使用Authentication

这张内容会比较有用,在使用token添加到头信息或者刷新过期token的时候

Integrate Basic Authentication

现在为ServiceGenerator类添加一个为请求增加认证(Authentication)的方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class ServiceGenerator {

public static final String API_BASE_URL = "https://your.api-base.url";

private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create());

public static <S> S createService(Class<S> serviceClass) {
return createService(serviceClass, null, null);
}

public static <S> S createService(
Class<S> serviceClass, String username, String password) {
if (!TextUtils.isEmpty(username)
&& !TextUtils.isEmpty(password)) {
String authToken = Credentials.basic(username, password);
return createService(serviceClass, authToken);
}

return createService(serviceClass, null, null);
}

public static <S> S createService(
Class<S> serviceClass, final String authToken) {
if (!TextUtils.isEmpty(authToken)) {
AuthenticationInterceptor interceptor =
new AuthenticationInterceptor(authToken);

if (!httpClient.interceptors().contains(interceptor)) {
httpClient.addInterceptor(interceptor);

builder.client(httpClient.build());
retrofit = builder.build();
}
}

return retrofit.create(serviceClass);
}
}

在新方法中添加了两个参数:username和password。这个和原来的方法是一样的,都可以用来创建建http请求并接收响应信息。

不同的是在第二个方法中添加了一个拦截器(AuthenticationInterceptor)。但是只有在为Retrofit提供了username和pasword之后你才能有这个拦截器,假如未添加这两个字段,你会得到和第一个方法一样的结果。

对于身份验证部分,必须调整给定usename和password的格式。 基本认证需要用两个值中间用冒号连接字符串。 此外,新创建(串联)字符串必须进行Base64编码。

大多数网络服务和API都会使用Authorization头信息来认证http请求。假如服务器认证方式不是使用这个Authorization,可以更改头信息的字段。如果以特定格式接收服务器的响应信息,Accept Header非常重要。

下面是AuthenticationInterceptor的定义类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class AuthenticationInterceptor implements Interceptor {

private String authToken;

public AuthenticationInterceptor(String token) {
this.authToken = token;
}

@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();

Request.Builder builder = original.newBuilder()
.header("Authorization", authToken);

Request request = builder.build();
return chain.proceed(request);
}
}

使用

现在你只需要调用 ServiceGenerator 类中的新方法就可以使用了。

请求方法:

1
2
3
4
public interface LoginService {  
@POST("/login")
Call<User> basicLogin();
}

创建http请求:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
LoginService loginService =  
ServiceGenerator.createService(LoginService.class, "user", "secretpassword");
Call<User> call = loginService.basicLogin();
call.enqueue(new Callback<User >() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
if (response.isSuccessful()) {
// user object available
} else {
// error response, no access to resource?
}
}

@Override
public void onFailure(Call<User> call, Throwable t) {
// something went completely south (like no internet connection)
Log.d("Error", t.getMessage());
}
}

ServiceGenerator方法将创建包含定义的授权头的HTTP客户端。 一旦调用loginService的basicLogin方法,提供的凭据将自动传递到请求的API端点。

安卓上的Token认证

Integrate Token Authentication

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class ServiceGenerator {

public static final String API_BASE_URL = "https://your.api-base.url";

private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create());

public static <S> S createService(Class<S> serviceClass) {
return createService(serviceClass, null);
}

public static <S> S createService(
Class<S> serviceClass, final String authToken) {
if (!TextUtils.isEmpty(authToken)) {
AuthenticationInterceptor interceptor =
new AuthenticationInterceptor(authToken);

if (!httpClient.interceptors().contains(interceptor)) {
httpClient.addInterceptor(interceptor);

builder.client(httpClient.build());
retrofit = builder.build();
}
}

return retrofit.create(serviceClass);
}
}

在上边的方法中,使用token作为参数传递到方法中,然后用拦截器添加头信息。(其实和上一节一样的东西)

Example Usage

1
2
3
4
public interface UserService {  
@POST("/me")
Call<User> me();
}

下面创建请求:

1
2
3
4
UserService userService =  
ServiceGenerator.create(UserService.class, "auth-token");
Call<User> call = userService.me();
User user = call.execute().body();

使用Retrofit上传下载文件

Upload Files With Retrofit 2

使用Retrofit 2,您需要使用OkHttp的RequestBody或MultipartBody.Part类,并将您的文件封装到请求正文中。

1
2
3
4
5
6
7
8
public interface FileUploadService {  
@Multipart
@POST("upload")
Call<ResponseBody> upload(
@Part("description") RequestBody description,
@Part MultipartBody.Part file
);
}

在上边的代码中:
首先你需要声明Call的注解为@Multipart请求。

@Part注解中的description,是一个字符串被封装在RequestBody中。

另一个@Part中的是一个MultipartBodu.Part,这个类允许在请求中加入文件,包括二进制文件。

Android Client Code

下面讲解上传文件,继续使用前边的ServiceGenerator类,下边的代码中显示了以文件的Uri作为参数传给uploadFile(Uri fileUri)方法。你启动了新的Intent来选择文件,将会在onActivityResult()方法中返回文件的Uri。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
private void uploadFile(Uri fileUri) {  
// create upload service client
FileUploadService service =
ServiceGenerator.createService(FileUploadService.class);

// https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
// use the FileUtils to get the actual file by uri
File file = FileUtils.getFile(this, fileUri);

// create RequestBody instance from file
RequestBody requestFile =
RequestBody.create(
MediaType.parse(getContentResolver().getType(fileUri)),
file
);

// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
MultipartBody.Part.createFormData("picture", file.getName(), requestFile);

// add another part within the multipart request
String descriptionString = "hello, this is description speaking";
RequestBody description =
RequestBody.create(
okhttp3.MultipartBody.FORM, descriptionString);

// finally, execute the request
Call<ResponseBody> call = service.upload(description, body);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call,
Response<ResponseBody> response) {
Log.v("Upload", "success");
}

@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("Upload error:", t.getMessage());
}
});
}

上面的代码用于初始化数据并上传文件。RequestBody类来自OkHttp,它的.create()方法需要传递两个参数,媒体类型和实际数据。媒体类型可以是OkHttp提供的请求常量如:okhttp3.MultipartBody.FORM。文件的媒体类型最好是实际的内容类型。例如,PNG图像应该有image / png。我们的代码中使用getContentResolver().getType(fileUri)调用来计算内容类型,然后使用MediaType.parse()将结果解析为OkHttp的媒体类型。

然后添加封装到MultipartBody.Part实例中的文件。这是您需要使用从客户端适当地上传文件。此外,您可以在createFormData()方法中添加原始文件名,并在后端重复使用它。

Remember the Content-Type

请注意Retrofit的内容类型。如果你拦截底层的OkHttp客户端并将内容类型更改为application / json,则您的服务器可能存在反序列化过程的问题。

Exemplary Hapi Server for File Uploads

搭建一个简单的hapi服务器,使用POST方法,路径在/ upload。 此外,hapi不解析传入的请求,我们使用一个名为multiparty的Node.js库来进行解析。

在multiparty的解析函数的回调中,我们记录每个字段以显示其输出。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
method: 'POST',  
path: '/upload',
config: {
payload: {
maxBytes: 209715200,
output: 'stream',
parse: false
},
handler: function(request, reply) {
var multiparty = require('multiparty');
var form = new multiparty.Form();
form.parse(request.payload, function(err, fields, files) {
console.log(err);
console.log(fields);
console.log(files);

return reply(util.inspect({fields: fields, files: files}));
});
}
}

输出日志:

1
2
3
4
5
6
7
8
null  
{ description: [ 'hello, this is description speaking' ] }
{ picture:
[ { fieldName: 'picture',
originalFilename: '20160312_095248.jpg',
path: '/var/folders/rq/q_m4_21j3lqf1lw48fqttx_80000gn/T/X_sxX6LDUMBcuUcUGDMBKc2T.jpg',
headers: [Object],
size: 39369 } ] }

上传多个文件

为你的FileUploadService类添加一个新的方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public interface FileUploadService {  
// previous code for single file uploads
@Multipart
@POST("upload")
Call<ResponseBody> uploadFile(
@Part("description") RequestBody description,
@Part MultipartBody.Part file);

// new code for multiple files
@Multipart
@POST("upload")
Call<ResponseBody> uploadMultipleFiles(
@Part("description") RequestBody description,
@Part MultipartBody.Part file1,
@Part MultipartBody.Part file2);
}

只需要向方法中添加 @Part MultipartBody.Part file即可。目前uploadMultipleFiles()支持上传两个文件,你也可以根据需求动态添加文件数量。

现在来看使用方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@NonNull
private RequestBody createPartFromString(String descriptionString) {
return RequestBody.create(
okhttp3.MultipartBody.FORM, descriptionString);
}

@NonNull
private MultipartBody.Part prepareFilePart(String partName, Uri fileUri) {
// https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
// use the FileUtils to get the actual file by uri
File file = FileUtils.getFile(this, fileUri);

// create RequestBody instance from file
RequestBody requestFile =
RequestBody.create(
MediaType.parse(getContentResolver().getType(fileUri)),
file
);

// MultipartBody.Part is used to send also the actual file name
return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
}

createPartFromString()可用于分段上传文件。prepareFilePart()方法创建了一个MultipartBody.Part对象,这个对象 包含一个文件,像照片或视频。在Retrofit2中需要使用MultipartBody.Part来封装文件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Uri file1Uri = ... // get it from a file chooser or a camera intent  
Uri file2Uri = ... // get it from a file chooser or a camera intent

// create upload service client
FileUploadService service =
ServiceGenerator.createService(FileUploadService.class);

// create part for file (photo, video, ...)
MultipartBody.Part body1 = prepareFilePart("video", file1Uri);
MultipartBody.Part body2 = prepareFilePart("thumbnail", file2Uri);

// add another part within the multipart request
RequestBody description = createPartFromString("hello, this is description speaking");

// finally, execute the request
Call<ResponseBody> call = service.uploadMultipleFiles(description, body1, body2);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call,
Response<ResponseBody> response) {
Log.v("Upload", "success");
}

@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("Upload error:", t.getMessage());
}
});

使用@PartMap上传多个文件

假如你只需要上传一个文件,你可以使用@Part来完成:

1
2
3
4
5
6
7
8
public interface FileUploadService {  
// previous code for single description
@Multipart
@POST("upload")
Call<ResponseBody> uploadFile(
@Part("description") RequestBody description,
@Part MultipartBody.Part file);
}

但是在需要上传多个文件并且单独配置一些属性时,使用这个方法就会出现问题。

Retrofit提供了一个简单的解决办法,使用@PartMap注解。这个方法在你的表单非常长但是只有一部分会在运行时发送非常有用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public interface FileUploadService {  
// declare a description explicitly
// would need to declare
@Multipart
@POST("upload")
Call<ResponseBody> uploadFile(
@Part("description") RequestBody description,
@Part MultipartBody.Part file);

@Multipart
@POST("upload")
Call<ResponseBody> uploadFileWithPartMap(
@PartMap() Map<String, RequestBody> partMap,
@Part MultipartBody.Part file);
}

请务必使用Map 实现作为请求的@PartMap部分的参数类型。 如上所述,这允许您发送依赖于运行时的数据列表以及您的文件。 PartMap后的括号是可选的。 如果要指定编码,则需要使用它们,类似于FieldMaps中的内容编码。

第二部分是用数据填充Map。 在前面的教程中,我们介绍了两个帮助方法来为String变量和文件变量创建RequestBody:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@NonNull
private MultipartBody.Part prepareFilePart(String partName, Uri fileUri) {
// https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
// use the FileUtils to get the actual file by uri
File file = FileUtils.getFile(this, fileUri);

// create RequestBody instance from file
RequestBody requestFile =
RequestBody.create(
MediaType.parse(getContentResolver().getType(fileUri)),
file
);

// MultipartBody.Part is used to send also the actual file name
return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);

使用方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Uri fileUri = ... // from a file chooser or a camera intent

// create upload service client
FileUploadService service =
ServiceGenerator.createService(FileUploadService.class);

// create part for file (photo, video, ...)
MultipartBody.Part body = prepareFilePart("photo", fileUri);

// create a map of data to pass along
RequestBody description = createPartFromString("hello, this is description speaking");
RequestBody place = createPartFromString("Magdeburg");
RequestBody time = createPartFromString("2016");

HashMap<String, RequestBody> map = new HashMap<>();
map.put("description", description);
map.put("place", place);
map.put("time", time);

// finally, execute the request
Call<ResponseBody> call = service.uploadFileWithPartMap(map, body);
call.enqueue(...);

下载文件

How to Specify the Retrofit Request

下载文件类似于GET方法:

1
2
3
4
5
6
7
// option 1: a resource relative to your base URL
@GET("/resource/example.zip")
Call<ResponseBody> downloadFileWithFixedUrl();

// option 2: using a dynamic URL
@GET
Call<ResponseBody> downloadFileWithDynamicUrlSync(@Url String fileUrl);

方法1是下载一个固定网址的文件,请注意Call中的泛型,一定要是ResponseBody类型。

方法2是在代码中传入URL作为下载地址。

How to Call the Request

发出请求:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
FileDownloadService downloadService = ServiceGenerator.create(FileDownloadService.class);

Call<ResponseBody> call = downloadService.downloadFileWithDynamicUrlSync(fileUrl);

call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccess()) {
Log.d(TAG, "server contacted and has file");

boolean writtenToDisk = writeResponseBodyToDisk(response.body());

Log.d(TAG, "file download was a success? " + writtenToDisk);
} else {
Log.d(TAG, "server contact failed");
}
}

@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e(TAG, "error");
}
});

上边的代码中writeResponseBodyToDisk()是存盘,下边讲解。

How to Save the File

writeResponseBodyToDisk()方法将ResponseBody转换为文件存放发到存储当中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
private boolean writeResponseBodyToDisk(ResponseBody body) {  
try {
// todo change the file location/name according to your needs
File futureStudioIconFile = new File(getExternalFilesDir(null) + File.separator + "Future Studio Icon.png");

InputStream inputStream = null;
OutputStream outputStream = null;

try {
byte[] fileReader = new byte[4096];

long fileSize = body.contentLength();
long fileSizeDownloaded = 0;

inputStream = body.byteStream();
outputStream = new FileOutputStream(futureStudioIconFile);

while (true) {
int read = inputStream.read(fileReader);

if (read == -1) {
break;
}

outputStream.write(fileReader, 0, read);

fileSizeDownloaded += read;

Log.d(TAG, "file download: " + fileSizeDownloaded + " of " + fileSize);
}

outputStream.flush();

return true;
} catch (IOException e) {
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}

if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
return false;
}
}

在转换文件的时候会将文件放到内存中,所以下载大文件时不要使用这种方法。

Beware with Large Files: Use @Streaming!

为了防止下载大文件时占用内存过多,我们必须使用@Streaming注解来解决这个问题:

1
2
3
@Streaming
@GET
Call<ResponseBody> downloadFileWithDynamicUrlAsync(@Url String fileUrl);

这样就能使用流来传送文件了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
final FileDownloadService downloadService =  
ServiceGenerator.create(FileDownloadService.class);

new AsyncTask<Void, Long, Void>() {
@Override
protected Void doInBackground(Void... voids) {
Call<ResponseBody> call = downloadService.downloadFileWithDynamicUrlSync(fileUrl);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccess()) {
Log.d(TAG, "server contacted and has file");

boolean writtenToDisk = writeResponseBodyToDisk(response.body());

Log.d(TAG, "file download was a success? " + writtenToDisk);
}
else {
Log.d(TAG, "server contact failed");
}
}
return null;
}
}.execute();