"Network" app (Retorfit2+rxjava) +javaweb (server) RETROFIT2 official documentation practices

Source: Internet
Author: User
Tags image png

Official Document: http://square.github.io/retrofit/
The following actions are performed when the retrofit environment is configured properly.

Tjstudy: Write in front, development environment

App Environment:
Android Studio 2.1.1
Minsdkversion 14
Targetsdkversion 23

Javaweb Server Environment:
MyEclipse 10
JDK 1.6

first, the most basic Mark

@GET @POST Tags : The most basic token of network access mode
Specifies the access method, which is typically written to the access address, and can be sorted if the data is obtained.
recommendation : Base_url, it is best to end with/@GET the address in the @POST does not begin/start.

@GET("users/list ")@POST("users/list?dort=asc")
second, POST and get mode, Universal Retorfit tag

POST GET Generic:@Path @Query @QueryMap @Header
The two common tags: mainly refers to the use of @post and @get can be used to receive data information, display the same effect, in real development, according to the requirements of the network to use the way to choose .
Most of the effects shown below are @get,post methods that directly change the GET to post view.

1. @Path: Specify Access Path
@GET("{name}/UploadParam")Observable<ResponseBody> test(@Path("name")String name);

A dynamically passed string will replace {name} as the new access address
This time the address of the visit is, Base_url+name+/uploadparam

2, @Query: Submit Parameters--not form submission, just ordinary submission
@GET("servlet/UploadParam")Observable<ResponseBody> testQuery(@Query("name") String name);

Server results:

3, @QueryMap: Is the @query of the collection form, can carry more parameters
@GET("group/{id}/users")Call<List<User>> groupList(@Path("id"Map<StringString> options);

Just put the parameters you want to carry in the map collection and pass them in.

4. @Header: Add Header information to network access
@Headers({        "appkey:tjstudy _ 2016 10 23"})@GET("servlet/HeaderTest")Observable<ResponseBody> testHeader(@Query("name") String name);

Server results:

@Header can also be placed directly into the actual request parameters, the effect is consistent with the above

@GET("servlet/HeaderTest")Observable<ResponseBody> testHeader(@Header(“appkey”) String appkey,@Query("name") String name);
three, must post method (@body @FormUrlEncoded @Multipart)

Using get mode + any of the above indicators will be an error. And these three tags can not be mixed, otherwise it will be an error.

1. @Body: Upload an object
@POST("servlet/TestBody")Observable<ResponseBody> testBody(       @BodyUser user);

Server results:

can I upload two objects?
Add another user to the above code, direct error ... it seems that only one object can be uploaded

2, @FormUrlEncoded: Form submission and @field pairing, during the visit, there is at least one @field in the parameters
@FormUrlEncoded@POST("servlet/TestFormUrlEncodes")Observable<ResponseBody> testFormUrlEncoded(        @Field("param1") String first,        @Field("param2") String last);

Server results:

Note :in @FormUrlEncoded tagged method, at least one parameter must be a parameter of the @field tag, otherwise an error will be found . They are paired, don't break them apart. Other parameters can be other tags, such as: @Query (although not necessary, but at least this situation will not be an error).

3, @Multipart: File upload and @part pairing during access, there is at least one @part in the parameters

Requestbody can encapsulate what type, @Multipart can upload such type of data to the server. Requestbody can encapsulate text, picture files, audio files, etc.

Here are the picture files.
How the server receives the files, which are received here using FileUpload (need to introduce fileupload related packages commons-fileupload-1.3 and commons-io-1.2 can be found in the code). Main code:

PrintWriter pw = Response.getwriter ();//Create File Project Factory objectDiskfileitemfactory factory =NewDiskfileitemfactory ();//Set File upload pathFile Uploaddir =NewFile ( This. Getservletcontext (). Getrealpath ("/upload/"));//Set File upload path to project name/upload/System. out. println ("File Upload path ="+ Uploaddir);if(!uploaddir.exists ()) {//If the folder does not exist, createUploaddir.mkdirs (); }//Gets the default temporary file save path for the system, which is the Temp folder under the Tomcat root directoryString temp = System.getproperty ("Java.io.tmpdir");//Set buffer size to 5MFactory.setsizethreshold (1024x768*1024x768*5);//Set temporary folder to tempFactory.setrepository (NewFile (temp));//Factory instancing Upload component, Servletfileupload used to parse file upload requestServletfileupload servletfileupload =NewServletfileupload (Factory);Try{list<fileitem> List = servletfileupload.parserequest (request); System. out. println ("Number of files ="+ list); for(Fileitem fileitem:list) {if(fileitem==NULL) {System. out. println ("The retrieved file is empty"); Break; } File File =NewFile (Uploaddir, fileitem.getfieldname () +". png");if(!file.exists ()) {//file does not exist before creatingFileitem.write (file);//Save fileSystem. out. println ("file name:"+ File.getname ()); }} pw.write ("{\" message\ ": \" upload succeeded \ "}"); System. out. println ("{\" message\ ": \" upload succeeded \ "}"); }Catch(Exception e) {Pw.write ("{\" message\ ": \" upload failed \ "}"); System. out. println ("{\" message\ ": \" upload failed \ "}"); }
1), @Mutipart + requestbody on the flyer file
File imageFile = new File(Environment.getExternalStorageDirectory().getPath(),"123.png");RequestBody imageRequestBody = RequestBody.create(MediaType.parse("image/png"), imageFile);
@Multipart@POST("servlet/TestMultipart")Observable<ResponseBody> testSingleMultipart(        @Part("photo") RequestBody image);

Server results:

2), @Mutipart + requestbody on flyer files and parameters

Since the files uploaded here and the received path are the same, before the new operation, you need to first delete the uploaded files.

@Multipart@POST("servlet/TestSingleMultipartParam")Observable<ResponseBody> testSingleMultipartParam(        @Part("photo") RequestBody image,        @Query("des") String des);

cannot use @formurlencoded to submit the parameter, the use will report an error .
Server results:

3), @Mutipart + requestbody upload multiple files and parameters
@Multipart@POST("servlet/TestMultipartMoreFile")Observable<ResponseBody> testMoreMultipartParam(        @Part("photo1") RequestBody image1,        @Part("photo2") RequestBody image2,        @Query("des") String des);

The source file is just a picture
Server results:

4), @PartMap upload files and parameters
@Multipart@POST("servlet/TestPostMultipartBodyPart")Observable<ResponseBody> testMultipartBodyMap(        @Query("des") String des,        @PartMap Map<String, RequestBody> images);

Server results:

5), @Multipart file upload another way--multipartbody.part

Note :Multipartbody is a method of OKHTTP3 that does not exist in OKHTTP2. The Retrofit2 is used here, so the OKHTTP3 comes with it.
The relationship between it and Requestbody:

file file = new file (environment .getexternalstoragedirectory   () .getabsolutepath  () +  "123.png" )  Requestbody requestbody = Requestbody.create  (Mediatype.parse  (), file)  Parameter 1  array name, parameter 2  file name. Multipartbody Photo1part = Multipartbody .createformdata  ( "Pic1" , Span class= "hljs-string" > "Pic2" , requestBody1) ;   

Multipartbody.part is actually the encapsulation of requestbody.

@Multipart@POST("servlet/TestPostMultipartBodyPart")Observable<ResponseBody> testMultipartBody(        @Part("photo1") RequestBody image1,        @Part MultipartBody.Part image2,        @Query("des")String des);

Here are two ways to upload
Server results:

doubts: Clearly directly use Responsebody can complete file upload, why also use Multipartbody.part? doubts are not resolved, depending on the network access operation currently in contact.
What is Todo?

Also: How to download the file? Operation is relatively simple
The download file is primarily a convection operation, and the server writes the stream to the Responsebody and returns it to the client. The client gets to the stream and then takes action.

Four, complete demo

App

Demo
http://download.csdn.net/detail/u012391876/9662557

"Network" app (Retorfit2+rxjava) +javaweb (server) RETROFIT2 official documentation practices

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.