android okhttp文字图片文件同步异步请求封装
时间: 2024-10-29 20:20:19 浏览: 13
Android使用OkHttp进行网络同步异步操作
在Android中,OkHttp是一个流行的HTTP客户端库,常用于处理网络请求。对于文本、图片等文件的同步和异步请求封装,你可以按照以下步骤进行:
1. 引入依赖:首先需要在你的build.gradle文件中添加OkHttp依赖:
```groovy
dependencies {
implementation 'com.squareup.okhttp3:okhttp:4.x.y'
}
```
这里`x.y`是你需要的具体版本。
2. 创建一个基础Request接口:
创建一个名为`BaseHttpRequest`的接口,定义通用的方法,如发送GET、POST请求并处理响应。
```java
public interface BaseHttpRequest<T> {
void execute(Request request, Callback<T> callback);
}
```
3. 实现同步请求(SyncRequest):
```java
public class SyncRequest<T> implements BaseHttpRequest<T> {
@Override
public T execute(Request request, Callback<T> callback) throws IOException {
Response response = client.newCall(request).execute();
return handleResponse(response, callback);
}
// ...处理响应的方法
}
```
4. 实现异步请求(AsyncRequest):
使用`ExecutorService`或者OkHttp的`enqueue`方法创建异步请求。
```java
public class AsyncRequest<T> implements BaseHttpRequest<T> {
private final OkHttpClient client;
private final Executor executor;
public AsyncRequest(OkHttpClient client, Executor executor) {
this.client = client;
this.executor = executor;
}
@Override
public void execute(Request request, Callback<T> callback) {
client.newCall(request).enqueue(new RealCallback<>(callback));
}
private static class RealCallback<T> implements Callback<T> {
private final Callback<T> originalCallback;
public RealCallback(Callback<T> callback) {
originalCallback = callback;
}
@Override
public void onFailure(Call call, IOException e) {
originalCallback.onFailure(call, e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) {
onFailure(call, new IOException("Unexpected code " + response));
return;
}
T result = handleResponse(response);
executor.execute(() -> originalCallback.onResponse(result, null));
}
}
// ...处理响应的方法
}
```
5. 根据需要发送不同类型的请求:
例如,可以创建`TextRequest`和`ImageRequest`作为具体的请求实例,分别处理文本和图片的下载:
```java
TextRequest textRequest = new TextRequest.Builder().url(url).build();
ImageRequest imageRequest = new ImageRequest.Builder(url, ...).build();
// 同步方式
new SyncRequest<String>().execute(textRequest, new TextCallback());
new SyncRequest<byte[]>().execute(imageRequest, new ImageCallback());
// 异步方式
executor.submit(() -> new AsyncRequest<>(client, executor).execute(textRequest, new TextCallback()));
executor.submit(() -> new AsyncRequest<>(client, executor).execute(imageRequest, new ImageCallback()));
```
6.
阅读全文