前面讲解了Volley
网络请求的使用,这章就来看看OkHttp
的使用。
调用的网址如下:
public static final String GET_HTTP = "http://gank.io/api/day/history";
public static final String POS_HTTP_WEATHER = "http://api.k780.com:88/";
public static final String POST_GITHUB_URL = "https://api.github.com/markdown/raw";
-
GET
同步使用
new Thread(new Runnable() {
@Override
public void run() {
try {
Request request = new Request.Builder()
.url(UrlUtils.GET_HTTP)
.method(UrlUtils.GET, null)
.build();
Response response = mOkHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
Log.e("LHC_OKHTTP", String.format("%svalue:%s", "getSyn->", response.body().string()));
} else {
Log.e("LHC_OKHTTP", String.format("%svalue:%s", "getSyn->", "请求失败"));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
-
GET
异步的使用
Request request = new Request.Builder()
.url(UrlUtils.GET_HTTP)
.method(UrlUtils.GET, null)
.build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e("LHC_OKHTTP", "请求失败");
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.body() != null) {
Log.e("LHC_OKHTTP", "请求成功");
Log.e("LHC_OKHTTP", String.format("%svalue:%s", "getAsyn->", response.body().string()));
} else {
Log.e("LHC_OKHTTP", String.format("%svalue:%s", "getAsyn->", response.networkResponse().toString()));
}
runOnUiThread(new Runnable() {
@Override
public void run() {
ToastUtils.showShort("请求成功");
}
});
}
});
-
POST
的同步使用
new Thread(new Runnable() {
@Override
public void run() {
try {
RequestBody body = new FormBody.Builder().add("app", "weather.future")
.add("weaid", "1").add("appkey", "10003").add("sign",
"b59bc3ef6191eb9f747dd4e83c99f2a4").add("format", "json")
.build();
Request request = new Request.Builder()
.url(UrlUtils.POS_HTTP_WEATHER)
.post(body)
.build();
Response response = mOkHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
Log.e("LHC_OKHTTP", String.format("%svalue:%s", "postSyn->", response.body().string()));
} else {
Log.e("LHC_OKHTTP", String.format("%svalue:%s", "postSyn->", "请求失败"));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
-
POST
异步使用
RequestBody body = new FormBody.Builder().add("app", "weather.future")
.add("weaid", "1").add("appkey", "10003").add("sign",
"b59bc3ef6191eb9f747dd4e83c99f2a4").add("format", "json")
.build();
Request request = new Request.Builder()
.url(UrlUtils.POS_HTTP_WEATHER)
.post(body)
.build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e("LHC_OKHTTP", "postAsyn():请求失败");
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.body() != null) {
Log.e("LHC_OKHTTP", String.format("%svalue:%s", "postAsyn->", response.body().string()));
} else {
Log.e("LHC_OKHTTP", String.format("%svalue:%s", "postAsyn->", response.networkResponse().toString()));
}
runOnUiThread(new Runnable() {
@Override
public void run() {
ToastUtils.showShort("请求成功");
}
});
}
});
}
-
POST
异步传String
RequestBody body = RequestBody.create(MediaType.parse("text/plain;charset=utf-8"), "api.github.com/markdown/raw");
Request request = new Request.Builder()
.url(UrlUtils.POST_GITHUB_URL)
.post(body)
.build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e("LHC_OKHTTP", "postAsynString():请求失败");
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.body() != null) {
Log.e("LHC_OKHTTP", String.format("%svalue:%s", "postAsynString->", response.body().string()));
} else {
Log.e("LHC_OKHTTP", String.format("%svalue:%s", "postAsynString->", response.networkResponse().toString()));
}
runOnUiThread(new Runnable() {
@Override
public void run() {
ToastUtils.showShort("请求成功");
}
});
}
});
-
POST
异步传文件
File file = new File(Environment.getExternalStorageDirectory()+"/test.txt");//传递的文件地址
RequestBody body = RequestBody.create(MediaType.parse("text/x-markdown;charset=utf-8"), file);
Request request = new Request.Builder()
.url(UrlUtils.POST_GITHUB_URL)
.post(body)
.build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e("LHC_OKHTTP", "postAsynFile():请求失败");
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.body() != null) {
Log.e("LHC_OKHTTP", String.format("%svalue:%s", "postAsynFile->", response.body().string()));
} else {
Log.e("LHC_OKHTTP", String.format("%svalue:%s", "postAsynFile->", response.networkResponse().toString()));
}
runOnUiThread(new Runnable() {
@Override
public void run() {
ToastUtils.showShort("请求成功");
}
});
}
});
-
POST
异步传流
RequestBody body = new RequestBody() {
@Nullable
@Override
public MediaType contentType() {
return MediaType.parse("text/x-markdown;charset=utf-8");
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
sink.writeUtf8("Number:\n");
for (int i = 2; i <= 997; i++) {
sink.writeUtf8(String.format(" * %s = %s\n", i, factor(i)));
}
}
};
Request request = new Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(body)
.build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e("LHC_OKHTTP", "postAsynStream():请求失败");
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.body() != null) {
Log.e("LHC_OKHTTP", String.format("%svalue:%s", "postAsynStream->", response.body().string()));
} else {
Log.e("LHC_OKHTTP", String.format("%svalue:%s", "postAsynStream->", response.networkResponse().toString()));
}
runOnUiThread(new Runnable() {
@Override
public void run() {
ToastUtils.showShort("请求成功");
}
});
}
});
}
private String factor(int n) {
for (int i = 2; i < n; i++) {
int x = n / i;
if (x * i == n) return factor(x) + " × " + i;
}
return Integer.toString(n);
}
-
GET
下载图片
Request request = new Request.Builder()
.url(UrlUtils.URL_IMAGE)
.build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e("LHC_OKHTTP", "downLoadFile():请求失败");
e.printStackTrace();
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
if (response != null && response.body() != null) {
ThreadUtil.getInstance().getExecutorService().execute(new Runnable() {//线程池生成新线程
@Override
public void run() {
writeFileToDisk(response);
}
});
}
}
});
private void writeFileToDisk(Response response) {
InputStream is = null;
FileOutputStream fos = null;
try {
byte[] buff = new byte[2048];
is = response.body().byteStream();
File filePath = new File(FILE_DIR);
if (!filePath.exists()) {
filePath.mkdirs();
}
final File file = new File(filePath, FILE_NAME);
fos = new FileOutputStream(file);
int len = 0;
while ((len = is.read(buff)) != -1) {
fos.write(buff, 0, len);
}
mHandler.post(new Runnable() {
@Override
public void run() {
Glide.with(OkHttpSimpleUseActivity.this).load(file.getAbsoluteFile()).into(ivShow);
}
});
fos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
-
POST
上传多个文件
List<File> files = new ArrayList<>();
files.add(new File(Environment.getExternalStorageDirectory() + File.separator + "crop_image.jpg"));
files.add(new File(Environment.getExternalStorageDirectory() + File.separator + "temp.png"));
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
for (File file : files) {
String filePath = file.getAbsolutePath();
String fileName = filePath.substring(filePath.lastIndexOf("/"));
builder.addFormDataPart("files", fileName, MultipartBody.create(MediaType.parse("application/octet-stream"), file));//这里的参数"files"是需要传递给服务器的参数名称
}
Request request = new Request.Builder()
.url(UrlUtils.URL_UPLOAD)
.post(builder.build())
.build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e("LHC_OKHTTP", "upLoadFile():请求失败");
e.printStackTrace();
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
Log.e("LHC_OKHTTP", "body:" + response.body().string());
ToastUtils.showShort("上传成功");
}
});
-
OkHttp
简单的二次封装
public class OkHttpHelper {
private static OkHttpHelper okHttpHelper = null;
private static OkHttpClient okHttpClient = null;
public static OkHttpHelper getInstance() {
if (okHttpHelper == null) {
synchronized (OkHttpHelper.class) {
if (okHttpHelper == null) {
okHttpHelper = new OkHttpHelper();
}
}
}
return okHttpHelper;
}
private static Handler mHandler = null;
synchronized Handler getHandler() {
if (mHandler == null) {
mHandler = new Handler();
}
return mHandler;
}
private synchronized OkHttpClient getOkHttpClient() {
if (okHttpClient == null) {
long cacheSize = 10 * 1024 * 1024;
String cachePath = Environment.getDownloadCacheDirectory() + File.separator;
File cacheFile = new File(cachePath, "OkHttp_Cache");
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
if (!cacheFile.exists() && !cacheFile.isDirectory()) {
cacheFile.mkdir();
}
}
Cache cache = new Cache(cacheFile, cacheSize);
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
Log.e("OkHttpLog", "" + message);
}
});
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
okHttpClient = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.cache(cache)//设置缓存
.addInterceptor(httpLoggingInterceptor)//设置输出日志拦截器
.addNetworkInterceptor(createHttpInterceptor())//设置网络拦截器
.build();
}
return okHttpClient;
}
/**
* 异步GET
*
* @param url 网址
* @param callback 回调
*/
public void doGet(String url, Callback callback) {
OkHttpClient okHttpClient = getOkHttpClient();
Request request = new Request.Builder().url(url).build();
okHttpClient.newCall(request).enqueue(callback);
}
/**
* 异步POST
*
* @param url 网址
* @param params 参数
* @param callback 回调
*/
public void doPost(String url, Map<String, String> params, Callback callback) {
OkHttpClient postClient = getOkHttpClient();
FormBody.Builder body = new FormBody.Builder();
for (String s : params.keySet()) {
body.add(s, params.get(s));
}
Request request = new Request.Builder().url(url).post(body.build()).build();
postClient.newCall(request).enqueue(callback);
}
public void doPostJson(String url, String jsonParams, Callback callback) {
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
Request request = new Request.Builder().url(url).post(body).build();
getOkHttpClient().newCall(request).enqueue(callback);
}
/**
* 上传文件
*
* @param url 上传文件地址
* @param files 文件 上传文件列表
* @param callback 回调
*/
public void uploadFileNew(String url, List<File> files, Callback callback) {
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
for (File file : files) {
String filePath = file.getAbsolutePath();
String fileName = filePath.substring(filePath.lastIndexOf("/"));
builder.addFormDataPart("files", fileName, MultipartBody.create(MediaType.parse("application/octet-stream"), file));
}
Request request = new Request.Builder().url(url).post(builder.build()).build();
getOkHttpClient().newCall(request).enqueue(callback);
}
/**
* 下载图片
*
* @param url 下载网址
* @param callback 回调
*/
public void downLoadFile(String url, Callback callback) {
Request request = new Request.Builder().url(url).build();
getOkHttpClient().newCall(request).enqueue(callback);
}
private static Interceptor createHttpInterceptor() {
return new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
int maxAge = 60 * 60;//有网络时设置缓存超时时间为1小时
int maxStale = 24 * 60 * 60;//没有网络时设置缓存超时时间为24小时
if (NetWorkUtils.isNetworkAvailable(StudyApplication.getContext())) {
//有网的情况下,只从网络上获取数据
request = request.newBuilder().cacheControl(CacheControl.FORCE_NETWORK).build();
} else {
//没有网的情况下,只从缓存中获取数据
request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
}
Response response = chain.proceed(request);
if (NetWorkUtils.isNetworkAvailable(StudyApplication.getContext())) {
response = response.newBuilder()
.removeHeader("Pragma")
.header("Cache_Control", "public, max-age=" + maxAge)
.build();
} else {
response = response.newBuilder()
.removeHeader("Pragma")
.header("Cache_Control", "public, only-if-cache, max-stale=" + maxStale)
.build();
}
return response;
}
};
}
}
- 下载文件回调封装
public abstract class DownFileCallback implements Callback{
private String FILE_DIR = Environment.getExternalStorageDirectory() + File.separator+"downImage";
private String FILE_NAME = "ok_"+System.currentTimeMillis()+".jpg";
private Handler mHandler = OkHttpHelper.getInstance().getHandler();
public abstract void onUI(String path);
public abstract void onFailed(Call call, IOException e);
@Override
public void onFailure(final Call call, final IOException e) {
mHandler.post(new Runnable() {
@Override
public void run() {
onFailed(call, e);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response != null && response.body() != null){
InputStream is = null;
FileOutputStream fos = null;
try {
byte[] buff = new byte[2048];
is = response.body().byteStream();
File filePath = new File(FILE_DIR);
if (!filePath.mkdirs()){
filePath.createNewFile();
}
final File file = new File(filePath, FILE_NAME);
fos = new FileOutputStream(file);
int len = 0;
while ((len = is.read(buff)) != -1){
fos.write(buff, 0 , len);
}
mHandler.post(new Runnable() {
@Override
public void run() {
onUI(file.getAbsolutePath());
}
});
fos.flush();
}catch (IOException e){
e.printStackTrace();
}finally {
if (is != null){
is.close();
}
if (fos != null){
fos.close();
}
}
}
}
}
-
GSON
解析回调封装
public abstract class GsonObjectCallback<T> implements Callback {
private Handler mHandler = OkHttpHelper.getInstance().getHandler();
public abstract void onUI(T t);
public abstract void onFailed(Call call, IOException e);
@Override
public void onFailure(final Call call, final IOException e) {
mHandler.post(new Runnable() {
@Override
public void run() {
onFailed(call, e);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response != null && response.body() != null) {
String result = response.body().string();
Class clz = this.getClass();
ParameterizedType type = (ParameterizedType) clz.getGenericSuperclass();
Type[] types = type.getActualTypeArguments();
Class<T> cls = (Class<T>) types[0];
Gson gson = new Gson();
final T t = gson.fromJson(result, cls);
mHandler.post(new Runnable() {
@Override
public void run() {
onUI(t);
}
});
}
}
}
- 封装
GET
异步 下载图片
OkHttpHelper.getInstance().downLoadFile(UrlUtils.URL_IMAGE, new DownFileCallback() {
@Override
public void onUI(String path) {
Glide.with(OkHttpFZUseActivity.this).load(new File(path)).into(ivShow);
}
@Override
public void onFailed(Call call, IOException e) {
Log.e("LHC_OKHTTP", "下载失败");
}
});
- 封装
POST
异步 上传图片
List<File> files = new ArrayList<>();
files.add(new File(Environment.getExternalStorageDirectory() + File.separator + "crop_image.jpg"));
files.add(new File(Environment.getExternalStorageDirectory() + File.separator + "temp.png"));
OkHttpHelper.getInstance().uploadFileNew(UrlUtils.URL_UPLOAD, files, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e("LHC_OKHTTP", "上传失败");
e.printStackTrace();
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
Log.e("LHC_OKHTTP", "body:" + response.body().string());
ToastUtils.showShort("上传成功");
}
});
- 封装
GET
异步
OkHttpHelper.getInstance().doGet(UrlUtils.GET_HTTP, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e("LHC_OKHTTP", "请求失败");
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
runOnUiThread(new Runnable() {
@Override
public void run() {
ToastUtils.showShort("请求成功");
}
});
}
});
- 封装
POST
异步
Map<String, String> params = new HashMap<>();
params.put("app", "weather.future");
params.put("weaid", "1");
params.put("appkey", "10003");
params.put("sign", "b59bc3ef6191eb9f747dd4e83c99f2a4");
params.put("format", "json");
OkHttpHelper.getInstance().doPost(UrlUtils.POS_HTTP_WEATHER, params, new GsonObjectCallback<Weathers>() {
@Override
public void onUI(Weathers weathers) {
ToastUtils.showShort(weathers.getResult().get(0).getCitynm());
}
@Override
public void onFailed(Call call, IOException e) {
ToastUtils.showShort("请求失败");
}
});