结构结合OkHttpClient+Retrofit+RXJava
1.Url接口
public interface BaseUrl {
String Base=“http://mobile.bwstudent.com/”;
//修改头像
String HeadLoadUrl=“movieApi/user/v1/verify/uploadHeadPic”;
}
2.apiServer接口 Retrofit注解接口
public interface ApiServer {
//修改头像
@POST
@Multipart
Observable PostHeadLoadUrl(@Url String url, @Part MultipartBody.Part flie);
}
3.NetUtlis类
public class NetUtlis {
private final ApiServer apiServer;
//构造函数
public NetUtlis() {
//拦截器
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//OKHTTP客户端
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(5, TimeUnit.SECONDS)
.connectTimeout(5,TimeUnit.SECONDS)
.writeTimeout(5,TimeUnit.SECONDS)
.addInterceptor(interceptor)
//自定义拦截器 可添加请求头
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request.Builder builder = request.newBuilder();
//添加请求头
SharedPreferences loginid = App.mContext.getSharedPreferences("loginid", Context.MODE_PRIVATE);
int userId = loginid.getInt("userId", 0);
String sessionId = loginid.getString("sessionId", "");
builder.addHeader("userId",userId+"");
builder.addHeader("sessionId",sessionId);
Request build = builder.build();
return chain.proceed(build);
}
})
.build();
//retrofit
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BaseUrl.Base)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
apiServer = retrofit.create(ApiServer.class);
}
//静态内部类单例模式
private static class NetCall{
private static NetUtlis netUtlis = new NetUtlis();
}
public static NetUtlis getInstance() {
return NetCall.netUtlis;
}
//接口回调
public interface NetCallBack<T>{
void onSucces(T t);
void onError(String error);
}
//网络判断
public boolean isWang(){
ConnectivityManager manager = (ConnectivityManager) App.mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = manager.getActiveNetworkInfo();
if (activeNetworkInfo!=null&&activeNetworkInfo.isAvailable()){
return true;
}else {
return false;
}
}
//修改头像方法
public void PostHeadLoadInfo(String url, File file, final NetCallBack callBack){
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part image = MultipartBody.Part.createFormData("image", file.getName(), requestBody);
apiServer.PostHeadLoadUrl(url,image).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<ResponseBody>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(ResponseBody responseBody) {
Gson gson= new Gson();
try {
String string = responseBody.string();
callBack.onSucces(string);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
}
4.FragmentActivity引用
public class HomeFragment extends BaseFragment {
private ImageView hradimage;
private Button bt;
@Override
protected void initData() {
//点击上传
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
File file = new File(Environment.getExternalStorageDirectory() + "/IMG_20200512_1250055.jpg");
//联网
mPresenter.IPresenterPostHeadLoadInfo(BaseUrl.HeadLoadUrl,file);
}
});
hradimage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent,100);
}
});
}
@Override
protected BasePresenter initPresenter() {
return new IPresenterImpl();
}
@Override
protected void initViews(View inflate) {
bt = inflate.findViewById(R.id.bt);
hradimage = inflate.findViewById(R.id.hradimage);
}
@Override
protected int initLaout() {
return R.layout.fragment_home;
}
@Override
public void onSucces(Object o) {
if (o instanceof String){
Toast.makeText(getContext(), ""+o.toString(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onError(String error) {
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri uri = data.getData();
hradimage.setImageURI(uri);
try {
Bitmap bitmap = BitmapFactory.decodeStream(getContext().getContentResolver().openInputStream(uri));
File file = new File(Environment.getExternalStorageDirectory() + "/lsd.jpg");
if (bitmap!=null){
FileOutputStream fileOutputStream = new FileOutputStream(Environment.getExternalStorageDirectory() + "/IMG_20200512_1250055.jpg");
bitmap.compress(Bitmap.CompressFormat.JPEG,50,fileOutputStream);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
//如果你是在Fragment实现onActivityResult必须在Activity引用一下才会执行 如果不是请忽略
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
homeFragment.onActivityResult(requestCode,resultCode,data);
}