今天和大家分享一个okhttp网络请求的实战案例,欢迎新手学生,大佬指点,话不多说直接上干货。
我是直接手动添加的架包,手动导入,记住一定要导入。添加依赖也可以哈,看个人爱好(要架包的私信或者留言,留邮箱,或者什么我发给你们)
然后在添加依赖:(允许我装个x用rxjava2了,加载图片用的是glide,支持多张上传图片)
implementation 'io.reactivex.rxjava2:rxjava:2.2.19'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation 'com.github.bumptech.glide:glide:4.11.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
implementation 'com.google.code.gson:gson:2.8.5'
最重要的一步来了,记住了 添加网络权限:
!--相机权限-->
<uses-permission android:name="android.permission.CAMERA" />
<!--读文件权限-->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!--使用特性-->
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.INTERNET" />
配置的都差不多准备完成了开始干代码吧:用rxjava接口是要有的:
public interface MyNetWorkCallback<T> {
void onSuccess(T t);
void onError(int errorCode, String errorMsg);
}
继续在上:
public interface IHttp {
<T> void get(String url, MyNetWorkCallback<T> callback);
<T> void get(String url, Map<String, String> params, MyNetWorkCallback<T> callback);
<T> void get(String url, Map<String, String> params, Map<String, String> headers, MyNetWorkCallback<T> callback);
<T> void post(String url, Map<String, String> params, MyNetWorkCallback<T> callback);
<T> void postraw(String url, String params, MyNetWorkCallback<T> callback);
<T> void postrawfile(String url, File file, MyNetWorkCallback<T> callback);
void upload(String url, String path, Map<String, String> params, String fileType, MediaType MEDIA_TYPE, final MyNetWorkCallback<String> callback);
<T> void download(String url,MyNetWorkCallback<String> callback);
void loadImage(String url, ImageView imageView);
}
这个类干啥来的忘记了,场时间不用了,但是也写山了,你们可以不用
public class HttpFactroy {
public static IHttp create(){
return OkHttpUtils.getInstance();
}
}
主要的类来了,单例走起:
public class OkHttpUtils implements IHttp {
private OkHttpClient okHttpClient;
//构造函数私有化
private OkHttpUtils() {
okHttpClient = new OkHttpClient.Builder().build();
}
private static OkHttpUtils okHttpUtils;
//提供一个公共的、静态的、返回值类型是当前本类的对象
public static OkHttpUtils getInstance() {
if (okHttpUtils == null) {
synchronized (OkHttpUtils.class) {
if (okHttpUtils == null) {
okHttpUtils = new OkHttpUtils();
}
}
}
return okHttpUtils;
}
private ProgressDialog progressDialog;
@Override
public <T> void get(String url, MyNetWorkCallback<T> callback) {
}
/**
* 上传多张图片及参数
*
* @param reqUrl URL地址
* @param paramssa 参数
* @param pic_key 上传图片的关键字
* @return
*/
public Observable<String> sendMultipart(final String reqUrl, final Map<String, String> paramssa, final String pic_key, final List<File> filessa) {
return Observable.create(new ObservableOnSubscribe<String>() {
@Override
public void subscribe(@NonNull ObservableEmitter<String> emitter) throws Exception {
MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
multipartBodyBuilder.setType(MultipartBody.FORM);
//遍历map中所有参数到builder
if (paramssa != null) {
for (String key : paramssa.keySet()) {
multipartBodyBuilder.addFormDataPart(key, paramssa.get(key));
}
}
//遍历paths中所有图片绝对路径到builder,并约定key如“upload”作为后台接受多张图片的key
if (filessa != null) {
for (File file : filessa) {
multipartBodyBuilder.addFormDataPart(pic_key, file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file));
}
}
//构建请求体
RequestBody requestBody = multipartBodyBuilder.build();
Request.Builder RequestBuilder = new Request.Builder();
RequestBuilder.url(reqUrl);// 添加URL地址
RequestBuilder.post(requestBody);
Request request = RequestBuilder.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
emitter.onError(e);
emitter.onComplete();
call.cancel();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String str = response.body().string();
emitter.onNext(str);
emitter.onComplete();
call.cancel();
}
});
}
});
}
/**
* 发送get请求
*
* @param url 请求地址
* @param params 请求参数
* @param callback 回调
* @param <T> 请求回来的数据对应的JavaBean
*/
@Override
public <T> void get(String url, Map<String, String> params, final MyNetWorkCallback<T> callback) {
StringBuffer sb = new StringBuffer(url);
if (params != null && params.size() > 0) {
sb.append("?");
Set<String> keys = params.keySet();
for (String key : keys) {
String value = params.get(key);
sb.append(key).append("=").append(value).append("&");
}
url = sb.deleteCharAt(sb.length() - 1).toString();
}
Request request = new Request.Builder().url(url).build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
App.context.runOnUiThread(new Runnable() {
@Override
public void run() {
//执行在主线程
callback.onError(404, e.getMessage().toString());
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String jsonData = response.body().string();
//执行在子线程中
App.context.runOnUiThread(new Runnable() {
@Override
public void run() {