Yesterday I introduced Retrofit to Rxjava, but there was a lot of duplicate code, so today I’m going to give you Retrofit wrapped up in three lines of code to request network data
- Implement the singleton pattern
- Create an interface for implementing Retrofit
- To encapsulate the Observer
- Create an interface to implement success and failure method returns
- GET use
- POST to use
- POST Uploads images and parameters
- Git address: [langyangyang] (https://github.com/langyangyangzzZ/Volley)
Implement the singleton pattern
package demo.ht.com.volley.retrofitHttp;
import android.text.TextUtils;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import io.reactivex.Observable;
import io.reactivex.android.BuildConfig;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
// Add the following dependencies:
Retrofit:
/ / implementation 'com. Squareup. Retrofit2: retrofit: 2.9.0'
/ / implementation 'com. Squareup. Retrofit2: converter - gson: 2.4.0'
//
//
// //glide4: // for image processing
/ / implementation 'com. Making. Bumptech. Glide: glide: 4.8.0'
/ / annotationProcessor 'com. Making. Bumptech. Glide: the compiler: 4.8.0'
//
// //RxJava:
/ / implementation "IO reactivex. Rxjava2: rxjava: 2.1.3" / / necessary rxjava2 dependency
/ / implementation "IO reactivex. Rxjava2: rxandroid: 2.0.1" / / necessary rxandrroid rely on, need to use when cutting the thread
/ / implementation 'com. Squareup. Retrofit2: adapter - rxjava2:2.4.0' / / need to rely on, and Retrofit must be used, will be mentioned below
//
/ / / * *
// * Log interceptor
/ / * /
/ / implementation 'com. Squareup. Okhttp3: logging - interceptor: 3.3.1'
/** * 20200721 szj */
public class NetManager {
private static volatile NetManager sNetManager;
private NetManager(a) {}public static NetManager getNetManager(a) {
if (sNetManager == null) {// Consider efficiency
synchronized (NetManager.class) {
if (sNetManager == null) {// Consider multiple threads
sNetManager = newNetManager(); }}}return sNetManager;
}
/ * * * *@paramT The first half of the incoming interface returns ApiServer * ending with /@param <T>
* @return* /
public <T> ApiServer getNetService(T... t) {
/ * * * using official log interceptor * add dependence: * implementation 'com. Squareup. Okhttp3: logging - interceptor: 3.3.1' * /
OkHttpClient.Builder builder = new OkHttpClient.Builder();
if (BuildConfig.DEBUG) {
// Log information interceptor
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);// You can select the interception level here
// Set the Debug Log mode
builder.addInterceptor(loggingInterceptor);
}
// Log interceptor
OkHttpClient build = builder.build();
ApiServer service = new Retrofit.Builder()
// Mutable parameters are passed in because the default interface apiserver.baseuri can also be used here.baseUrl(t ! =null&& t.length ! =0 && !TextUtils.isEmpty((String) t[0])? (String) t[0] : ApiServer.BaseUri)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(build)
.build().create(ApiServer.class);
return service;
}
/ * * * *@paramWhichApi ID number Identifies current requested data *@paramPObservable Interface for requests *@paramPresenterCallBack returns the value *@param <T>
*/
public <T> void method( final int whichApi,Observable<T> pObservable, final ICommonView presenterCallBack) {
pObservable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new BaseObserver() {
@Override
public void onSuccess(Object value) {
presenterCallBack.onSuccess(whichApi, value);
}
@Override
public void onFailed(Throwable value) { presenterCallBack.onFailed(whichApi, value); }}); }/** ** is used for POST requests to pass in key-value pairs to get RequestBody *@paramHashMap hashMap key-value pair *@return* /
public RequestBody getRequestBody(HashMap<String, String> hashMap) {
StringBuffer data = new StringBuffer();
if(hashMap ! =null && hashMap.size() > 0) {
Iterator iter = hashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
Object key = entry.getKey();
Object val = entry.getValue();
data.append(key).append("=").append(val).append("&");
}
}
String jso = data.substring(0, data.length() - 1);
RequestBody requestBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded; charset=utf-8"),jso);
returnrequestBody; }}Copy the code
Create an interface for implementing Retrofit
/** * is used to define a Retrofit interface */
public interface ApiServer {
public static String BaseUri = "https://gank.io/api/data/%E7%A6%8F%E5%88%A9/";
// http://hn216.api.yesapi.cn/
public static String GuoChuangYun_BaseUri = "http://hn216.api.yesapi.cn/";
}
Copy the code
To encapsulate the Observer
public abstract class BaseObserver implements Observer {
private Disposable d;
@Override
public void onSubscribe(Disposable d) {
this.d = d;
}
@Override
public void onNext(Object value) {
onSuccess(value);
dispose();
}
@Override
public void onError(Throwable e) {
onFailed(e);
dispose();
}
@Override
public void onComplete(a) {}public abstract void onSuccess(Object value);
public abstract void onFailed(Throwable value);
private void dispose(a) {
if (!d.isDisposed())
d.dispose();
}
}
Copy the code
Create an interface to implement success and failure method returns
public interface ICommonView<S> {
void onSuccess(int whichApi, S successResult);
void onFailed(int whichApi, Throwable failedResult);
}
Copy the code
GET use
NetManager netManager = NetManager.getNetManager();
ApiServer netService = netManager.getNetService(ApiServer.BaseUri);
//
netManager.method(ApiConfig.GET_DATA_MEINV, netService.getHttpMeiNvBean("8"."1"), this);
Copy the code
ICommonView interface was realized, onSuccess() and onFailed() methods were rewritten, and the current interface was judged by whichApi
@Override
public void onSuccess(int whichApi, Object successResult) {
if (whichApi == ApiConfig.GET_DATA_MEINV) {
MeiNvBean meiNvBean = (MeiNvBean) successResult;
mTv.setText("Successful use :\n"+ meiNvBean.toString()); }}@Override
public void onFailed(int whichApi, Throwable failedResult) {
mTv.setText("Failed to use :\n" + whichApi + "\n" + failedResult.getMessage());
}
Copy the code
POST to use
NetManager netManager = NetManager.getNetManager();
ApiServer netService = netManager.getNetService(ApiServer.GuoChuangYun_BaseUri);
Method one: / * * * through netManager. GetRequestBody RequestBody object * / ()
RequestBody requestBody = netManager.getRequestBody(stringHashMap);
netManager.method(ApiConfig.POST_UP_DATA_GUOCHUANGYUN,netService.getPOSTBodyGuoCHuangYunBean(requestBody),this);
/**@POSTCooperate with@BodyAnnotate request data */
// netManager.method(ApiConfig.POST_UP_DATA_GUOCHUANGYUN,netService.getPOSTBodyGuoCHuangYunBean(app_key),this);
/**@FormUrlEncodedCooperate with@FieldMapRequest data * Note: Want to use@FiledMapor@FiledYou have to use@FormUrlEncodedAnnotation declaration * use@FormUrlEncodedYou have to use@FiledMapor@Filed* /
// netManager.method(ApiConfig.POST_UP_DATA_GUOCHUANGYUN,netService.getPOSTGuoCHuangYunBean(stringHashMap),this);
Copy the code
The comments are very detailed. There are three ways to POST data; I’m not going to go through all of this and then implement the ICommonView interface just like GET, overriding the onSuccess() and onFailed() methods
@Override
public void onSuccess(int whichApi, Object successResult) {
if(whichApi == ApiConfig.POST_UP_DATA_GUOCHUANGYUN){ GuoChuangYunBean guoChuangYunBean = (GuoChuangYunBean) successResult; mTv.setText("Successful use :\n"+ guoChuangYunBean.toString()); }}@Override
public void onFailed(int whichApi, Throwable failedResult) {
mTv.setText("Failed to use :\n" + whichApi + "\n" + failedResult.getMessage());
}
Copy the code
POST Uploads images and parameters
// Method 1:
RequestBody requestBody = new MultipartBody.Builder().
setType(MultipartBody.FORM)
.addFormDataPart("app_key"."74D2E724FE2B69EF7EA3F38E9400CF71")
.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/png"), file))
.build();
// Method 2:
RequestBody fileRQ = RequestBody.create(MediaType.parse("image/png"), file);
MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), fileRQ);
RequestBody fb =RequestBody.create(MediaType.parse("text/plain"), "74D2E724FE2B69EF7EA3F38E9400CF71");
/** ** package */
NetManager netManager = NetManager.getNetManager();
ApiServer netService = netManager.getNetService(ApiServer.GuoChuangYun_BaseUri);
/** Method 1: * use@BodyAnnotation realizes image + parameter upload together */
// netManager.method(ApiConfig.UP_DATA_IMAEG, netService.getImageBean(requestBody), this);
/** Method 2: * use@MultipartAnnotations to cooperate@PartImplement separate upload parameters and separate upload pictures */
netManager.method(ApiConfig.UP_DATA_IMAEG, netService.uploadFile(fb,part), this);
Copy the code
ICommonView interface was also implemented, onSuccess() and onFailed() methods were rewritten, and the current interface was judged by whichApi.
@Override
public void onSuccess(int whichApi, Object successResult) {
if (whichApi == ApiConfig.UP_DATA_IMAEG) {
ImageBean imageBean = (ImageBean) successResult;
Glide.with(this)
.load(imageBean.getData().getUrl())
.apply(new RequestOptions().placeholder(R.mipmap.ic_launcher))
.into(mImage);
mTv.setText("Successful use :\n"+ imageBean.toString()); }}@Override
public void onFailed(int whichApi, Throwable failedResult) {
mTv.setText("Failed to use :\n" + whichApi + "\n" + failedResult.getMessage());
}
Copy the code
Git address:langyangyang
Creation is not easy, you have better comments please leave a message in the comment section! Thanks for watching