Hi, I haven’t updated it for a long time, but today I would like to introduce you to the framework that has been popular for a long time,Retrofit plus R xJava
- introduce
- advantages
- Use necessary actions
- Request method, request header, request parameter table introduction
- @ GET request:
- @ POST request
- Open the local album and select a picture to upload the picture
- @ Url using:
XJava to work with)
introduce
Retrofit is an enhanced version of OKHTTP that encapsulates okHTTP underneath. To be precise, Retrofit is an encapsulation of a RESTful HTTP Web request framework. Because the web request work is essentially done by OKHTTP, Retrofit is responsible for encapsulating the web request interface.
advantages
- Super decoupled
- Supports synchronous, asynchronous, and Rxjava
- You can configure different deserialization utility classes to parse different data, such as JSON and XML
- Request fast, easy to use flexible and simple
Use necessary actions
Add 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" // Required Rxjava2 dependency
implementation "IO. Reactivex. Rxjava2: rxandroid: 2.0.1." " // The rxandrroID dependency is required for thread cutting
implementation 'com. Squareup. Retrofit2: adapter - rxjava2:2.4.0' // Necessary dependencies, which must be used in conjunction with Retrofit, are discussed below
/** * log interceptor */
implementation 'com. Squareup. Okhttp3: logging - interceptor: 3.3.1'
Copy the code
Request method, request header, request parameter table introduction
Request method:
annotations | instructions |
---|---|
@GET | A get request |
@POST | A post request |
@PUT | Put request |
@DELETE | The delete request |
@PATCH | Patch request |
@HEAD | Head request: Used to update local resources |
@OPTIONS | The options request |
@HTTP | The PUT request replaces all of the above annotations with an annotation, which has three attributes: Method, Path, and hasBody |
This article focuses on the common @get, @post, and @HTTP requests.
Request header:
Request header annotation | instructions |
---|---|
@Headers | For adding fixed headers, you can add more than one at a time. Headers passing this annotation do not overwrite each other, but coexist |
@Header | Passed as a parameter to the method, used to add a non-fixed header that updates the existing request header |
This article does not cover request headers. Request headers can be written in code because too many annotations can be confusing, and it is not recommended to add headers using annotations.
Request parameters:
Request parameters | instructions |
---|---|
@Body | It is mostly used to send non-expressive data in POST requests. The instance object is converted into the corresponding string to pass parameters according to the conversion method, such as sending Json data using POST, and adding GsonConverterFactory converts the body into a Json string to pass |
@Filed | For POST requests, parameters are passed in form form with @fromurlcoded |
@FiledMap | Form fields in POST requests, passing multiple parameters, need to be used with @fromurlencoded |
@Part | Used for POST requests. Used with @multipart to upload a single file |
@PartMap | Used for POST requests. Used with @multipart to upload multiple files |
@Path | A placeholder in the Url |
@Query | Parameters used in Get requests |
@QueryMap | Similar to Query, used to determine form parameters |
@Url | Specify the request path |
Request and response formats:
Request and response format (markup) annotations | instructions |
---|---|
@FromUrlEncoded | @filedMap and @filed must be added when they are used |
@Multipart | @partMap and @Part must be added when used |
@Streaming | The response is returned as a byte stream, which by default loads all the data into memory without annotations, especially useful when downloading large files |
@ GET request:
Define an interface:
public interface ApiServer {
// Define the first half of the interface to request, note: this must end with /!!
public static String BaseUri = "https://gank.io/api/data/%E7%A6%8F%E5%88%A9/";
/** * is used by calling getMeiNvBen()@PathAnnotation, set the parameters passed to@GET() * Implement GET pass */
@GET("{number}/{index}")
Observable<MeiNvBean> getMeiNvBean(@Path("number")String number, @Path("index")String index);
/ * * * *@paramMethod Method of a network request (case sensitive) *@paramPath Network request address path *@paramHasBody has a request body *@return* /
@HTTP(method = "GET",path = "{number}/{index}" ,hasBody = false)
Observable<MeiNvBean> getHttpMeiNvBean(@Path("number")String number, @Path("index")String index);
}
Copy the code
My MeiNvBean class uses Postman software to request data and GsonFromat to get the corresponding entity class:
Get the MeiNvBean entity class:
package demo.ht.com.volley.bean;
import java.util.List;
public class MeiNvBean {
/** * error : false * results : [{" _id ":" 5 be14edb9d21223dd50660f8 ", "createdAt" : "the 2018-11-06 T08: thus. 656 z", "desc" : "2018-11-06", "publishedAt" : "the 2018-11-06 T 00:00:00. 0 z ", "the source", "web", "type" : "welfare", "url" : "https://img.lijinshan.site/images/8733844e0b954e7e8e29102cefa32dbf", "2 ": true," who ", "lijinshanmx"}, {" _id ":" 5 bcd71979d21220315c663fc ", "createdAt" : "the 2018-10-22 T06:43:35. 440 z", "desc" : "2018-10-22" , "publishedAt" : "the 2018-10-22 T00:00:00. 0 z", "source" : "web", "type" : "welfare", "url" : "https://img.lijinshan.site/images/0bc3ed0deda7 4674b45bebb140bb5928","used":true,"who":"lijinshanmx"},{"_id":"5bc434ac9d212279160c4c9e","createdAt":"2018-10-15T06:33:1 6.497 Z ", "desc" : "2018-10-15", "publishedAt" : "the 2018-10-15 T00:00:00. 0 Z", "source" : "web", "type" : "welfare", "url" : "https://img.lijinsh an.site/images/1635f0ffd94f40ff8058c2c4ff652e61","used":true,"who":"lijinshanmx"},{"_id":"5bbb0de09d21226111b86f1c","cre AtedAt ":" the 2018-10-08 T07:57:20. 978 z ", "desc" : "2018-10-08", "publishedAt" : "the 2018-10-08 T00:00:00. 0 z", "source" : "web", "type" : "welfare" ,"url":"https://img.lijinshan.site/images/e930b75f48ae40b0a23f827e619d76a3","used":true,"who":"lijinshanmx"},{"_id":"5ba 206 ec9d2122610aba3440 createdAt ", "" :" the 2018-09-19 T08: at 21:00. 295 z ", "desc" : "2018-09-19", "publishedAt" : "the 2018-09-19 T00:00:00. 0 z" , "the source", "web", "type" : "welfare", "url" : "https://img.lijinshan.site/images/d19c8feacc884e18898034c79e6e1a9d", "2" : true, "who" : "lijinshanmx"}, {" _id ":" 5 b9771a29d212206c1b383d0 ", "createdAt" : "the 2018-09-11 T07: them. 491 z", "desc" : "2018-09-11", "publishedA T ":" the 2018-09-11 T00:00:00. 0 z ", "source" : "web", "type" : "welfare", "url" : "https://img.lijinshan.site/images/38ddf2ca672345889343b574 8 ffce78d ", "2" : true, "who", "lijinshanmx"}, {" _id ":" 5 b830bba9d2122031f86ee51 ", "createdAt" : "the 2018-08-27 T04: they. 703 z", "des C ":" 2018-08-27 ", "publishedAt" : "the 2018-08-28 T00:00:00. 0 z", "source" : "web", "type" : "welfare", "url" : "https://img.lijinshan.site/imag es/a8aa7df22298413e9ca37c7a634e3425","used":true,"who":"lijinshanmx"},{"_id":"5b7b836c9d212201e982de6e","createdAt":"201 : the 8-08-21 T11 glorifying the. 989 z ", "desc" : "2018-08-21", "publishedAt" : "the 2018-08-21 T00:00:00. 0 z", "source" : "web", "type" : "welfare", "url" : "HTTP s://ws1.sinaimg.cn/large/0065oQSqly1fuh5fsvlqcj30sg10onjk.jpg","used":true,"who":"lijinshanmx"}] */
private boolean error;
private List<ResultsBean> results;
@Override
public String toString(a) {
return "MeiNvBean{" +
"error=" + error +
", results=" + results +
'} ';
}
public boolean isError(a) {
return error;
}
public void setError(boolean error) {
this.error = error;
}
public List<ResultsBean> getResults(a) {
return results;
}
public void setResults(List<ResultsBean> results) {
this.results = results;
}
public static class ResultsBean {
/** * _ID: 5be14edb9d21223DD50660F8 * createdAt: 2018-11-06T08:20:43.656z * desc: 2018-11-06t08:20:43.656z * publishedAt: 2018-11-06T00:00.0z * source: web * type: benefits * URL: https://img.lijinshan.site/images/8733844e0b954e7e8e29102cefa32dbf * used : true * who : lijinshanmx */
private String _id;
private String createdAt;
private String desc;
private String publishedAt;
private String source;
private String type;
private String url;
private boolean used;
private String who;
@Override
public String toString(a) {
return "ResultsBean{" +
"_id='" + _id + '\' ' +
", createdAt='" + createdAt + '\' ' +
", desc='" + desc + '\' ' +
", publishedAt='" + publishedAt + '\' ' +
", source='" + source + '\' ' +
", type='" + type + '\' ' +
", url='" + url + '\' ' +
", used=" + used +
", who='" + who + '\' ' +
'} ';
}
public String get_id(a) {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getCreatedAt(a) {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getDesc(a) {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getPublishedAt(a) {
return publishedAt;
}
public void setPublishedAt(String publishedAt) {
this.publishedAt = publishedAt;
}
public String getSource(a) {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getType(a) {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUrl(a) {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public boolean isUsed(a) {
return used;
}
public void setUsed(boolean used) {
this.used = used;
}
public String getWho(a) {
return who;
}
public void setWho(String who) {
this.who = who; }}}Copy the code
Use the most primitive unwrapped GET request data:
Retrofit apiServer = new Retrofit.Builder().
addCallAdapterFactory(RxJava2CallAdapterFactory.create()).
addConverterFactory(GsonConverterFactory.create())
.baseUrl(ApiServer.BaseUri)
.build();
// apiServer.create(ApiServer.class).getHttpMeiNvBean("8","1")
apiServer.create(ApiServer.class).getMeiNvBean("8"."1")
.subscribeOn(Schedulers.io())/ / IO thread
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<MeiNvBean>() {
@Override
public void onSubscribe(Disposable d) {}@Override
public void onNext(MeiNvBean meiNvBean) {
mTv.setText(meiNvBean.toString());
Log.i("szjonNex", meiNvBean.toString());
}
@Override
public void onError(Throwable e) {
mTv.setText("Request error :" + e.getMessage());
Log.i("onError", e.getMessage());
}
@Override
public void onComplete(a) {}});Copy the code
Come to Kangkang Log:
@ POST request
Define the interface first to implement the declaration of the request interface:
public interface ApiServer {
// Define the first half of the interface to request, note: this must end with /!!
public static String GuoChuangYun_BaseUri = "http://hn216.api.yesapi.cn/";
/ * * * *@paramFormUrlEncoded uploads must be added via FieldMap@FormUrlEncodedThe annotation indicates the declaration form upload *@return* /
@FormUrlEncoded
@POST("? s=App.User.Search")
Observable<GuoChuangYunBean> getPOSTGuoCHuangYunBean(@FieldMap Map<String ,String > map);
/ * * * *@paramFormBody app_key = new formBody.builder () *.add("key", "valye") *.build(); *@return* /
@POST("? s=App.User.Search")
Observable<GuoChuangYunBean> getPOSTBodyGuoCHuangYunBean(@Body RequestBody body);
}
Copy the code
Postman request POST interface, obtain parameters, obtain entity class through GsonFromat;
Get the GuoChuangYunBean entity class:
package demo.ht.com.volley.bean;
import java.util.List;
public class GuoChuangYunBean {
/ ret: * * * 200 * data: {" err_code ": 0," err_msg ":" ", "users" : []} * MSG: V3.1.0 YesApi App. The User. The Search * /
private int ret;
private DataBean data;
private String msg;
@Override
public String toString(a) {
return "GuoChuangYunBean{" +
"ret=" + ret +
", data=" + data +
", msg='" + msg + '\' ' +
'} ';
}
public int getRet(a) {
return ret;
}
public void setRet(int ret) {
this.ret = ret;
}
public DataBean getData(a) {
return data;
}
public void setData(DataBean data) {
this.data = data;
}
public String getMsg(a) {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public static class DataBean {
/** * err_code : 0 * err_msg : * users : [] */
private int err_code;
private String err_msg;
privateList<? > users;@Override
public String toString(a) {
return "DataBean{" +
"err_code=" + err_code +
", err_msg='" + err_msg + '\' ' +
", users=" + users +
'} ';
}
public int getErr_code(a) {
return err_code;
}
public void setErr_code(int err_code) {
this.err_code = err_code;
}
public String getErr_msg(a) {
return err_msg;
}
public void setErr_msg(String err_msg) {
this.err_msg = err_msg;
}
publicList<? > getUsers() {return users;
}
public void setUsers(List
users) {
this.users = users; }}}Copy the code
Request POST data using the most primitive request:
HashMap<String, String> stringHashMap = new HashMap<>();
stringHashMap.put("app_key"."74D2E724FE2B69EF7EA3F38E9400CF71");
FormBody app_key = new FormBody.Builder()
.add("app_key"."74D2E724FE2B69EF7EA3F38E9400CF71")
.build();
Retrofit apiServer = new Retrofit.Builder().
addCallAdapterFactory(RxJava2CallAdapterFactory.create()).
addConverterFactory(GsonConverterFactory.create())
.baseUrl(ApiServer.GuoChuangYun_BaseUri)
.build();
apiServer.create(ApiServer.class)
.getPOSTBodyGuoCHuangYunBean(app_key)// @body annotation upload
//.getPostGuochuangYunbean (stringHashMap)// @formurlencoded match @fieldMap
.subscribeOn(Schedulers.io())/ / IO thread
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<GuoChuangYunBean>() {
@Override
public void onSubscribe(Disposable d) {}@Override
public void onNext(GuoChuangYunBean guoChuangYunBean) {
Log.i("szjPOSTonNext"."\n"+guoChuangYunBean.toString());
mTv.setText("POST interface: \ n" + guoChuangYunBean.toString());
}
@Override
public void onError(Throwable e) {
mTv.setText("POST interface request error :\n" + e.getMessage());
}
@Override
public void onComplete(a) {}});Copy the code
Come to Kangkang Log:
Open the local album and select a picture to upload the picture
Open a local album. Apply for dynamic permission
// Open the local album
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/png");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(intent, REQUEST_PICTURE_CHOOSE);
Copy the code
Override the onActivityResult() method to get the selected image path and upload the image
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_PICTURE_CHOOSE) {
/** * select * from ** * where ** * from ** * /
Uri selectedImage = data.getData(); // Get the Uri of the photo returned by the system
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null.null.null);// Query the photo corresponding to the specified Uri from the system table
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String path = cursor.getString(columnIndex); // Get the photo path
Log.i("szjpath"."\t\t" + path);
// Upload the imageinitUpdata(path); }}Copy the code
Define the interface and set the request parameters:
public interface ApiServer {
public static String GuoChuangYun_BaseUri = "http://hn216.api.yesapi.cn/";
/ * * * *@paramBody Upload picture *@return* /
// @multiPart Note: @multipart is used in conjunction with @Part or @partmap.!!!!!!! cannot be used alone
@POST("? s=App.CDN.UploadImg")
Observable<ImageBean> getImageBean( @Body RequestBody file);
/ * * \ * *@paramBody Upload app_key *@paramFile Single image uploaded *@return* /
@Multipart
@POST("? s=App.CDN.UploadImg")
Observable<ImageBean> uploadFile(@Part("app_key") RequestBody body, @Part MultipartBody.Part file);
}
Copy the code
Fetch the data from Postman and fetch the entity class from GsonFragment.
File file = new File(path);
// 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");
Retrofit apiServer = new Retrofit.Builder().
addCallAdapterFactory(RxJava2CallAdapterFactory.create()).
addConverterFactory(GsonConverterFactory.create())
.baseUrl(ApiServer.GuoChuangYun_BaseUri)
.build();
apiServer.create(ApiServer.class)
//.getimageBean (requestBody) // @body image + parameter upload simultaneously
.uploadFile(requestBody,part) // @multipart uploads a single image and a single parameter with @Part
.subscribeOn(Schedulers.io())/ / IO thread
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<ImageBean>() {
@Override
public void onSubscribe(Disposable d) {}@Override
public void onNext(ImageBean imageBean) {
String url = imageBean.getData().getUrl();
Glide.with(RetrofitActivity.this)
.load(url)
.apply(new RequestOptions().placeholder(R.mipmap.ic_launcher))
.into(mImage);
mTv.setText("Image uploaded successfully :\n" + imageBean.toString());
Log.i("szjOnNext", imageBean.toString());
}
@Override
public void onError(Throwable e) {
Log.i("onError", e.getMessage());
mTv.setText("Failed to upload picture :\n" + e.getMessage());
}
@Override
public void onComplete(a) {}});Copy the code
I opened my album and uploaded a photo of my workout. Here’s the Kangkang effect:
Ha ha ha ha ha ha, the ugly, but also strange embarrassed, shy QvQ
@ Url using:
Here is an example of the GET interface:
public interface ApiServer {
@GET
Observable<MeiNvBean> getUrlMeiNvBean(@Url String url);
}
@UrlRetrofit apiServer =? Retrofit apiServer =new Retrofit.Builder().
addCallAdapterFactory(RxJava2CallAdapterFactory.create()).
addConverterFactory(GsonConverterFactory.create())
.baseUrl(ApiServer.BaseUri)
.build();
apiServer.create(ApiServer.class).getUrlMeiNvBean(ApiServer.BaseUri+"8/1")
.subscribeOn(Schedulers.io())/ / IO thread
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<MeiNvBean>() {
@Override
public void onSubscribe(Disposable d) {}@Override
public void onNext(MeiNvBean meiNvBean) {
mTv.setText(meiNvBean.toString());
Log.i("szjonNex", meiNvBean.toString());
}
@Override
public void onError(Throwable e) {
mTv.setText("Request error :" + e.getMessage());
Log.i("onError", e.getMessage());
}
@Override
public void onComplete(a) {}});Copy the code
All the effects of Kangkang bar:
This is a lot of repetitive code, so the next one is Retrofit, if you want to see itClick to view
Git link: Langyangyang.
Writing a blog is too tiring and easy to make mistakes. If you see any mistakes, please leave them in the comments section. Thank you for watching