/
BooksSupplier.java
75 lines (58 loc) · 1.73 KB
/
BooksSupplier.java
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package com.aswifter.material.book;
import android.support.annotation.NonNull;
import com.aswifter.material.common.AppClient;
import com.google.android.agera.Result;
import com.google.android.agera.Supplier;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
/**
* Created by chenyc on 16/4/27.
*/
public class BooksSupplier implements Supplier<Result<List<Book>>> {
public String key;
public void setKey(String key) {
this.key = key;
}
public BooksSupplier(String key) {
this.key = key;
}
OkHttpClient client = new OkHttpClient();
private static final String BASE_URL = "https://api.douban.com/v2/";
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
private List<Book> getBooks() {
Map<String, String >params = new HashMap<>();
params.put("q",key);
params.put("start","0");
params.put("end","50");
try {
BookResponse bookResponse = AppClient.httpService.getBooks(params).execute().body();
return bookResponse.getBooks();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
@NonNull
@Override
public Result<List<Book>> get() {
List<Book> books = getBooks();
if (books == null) {
return Result.failure();
} else {
return Result.success(books);
}
}
}