Before the network request has been used okhttp, this period of time to understand the retrofit2, found more flexible than the okhttp of their package, all of his requests are implemented using interfaces, unlike Okhttp, in case you want to get a new callback, You have to re-encapsulate a method.
As soon as the project imports the Okhttp,retrofit default with the Okhttp request network, the returned type is call, then responds to Okhttp callback
Can be used with Rxjava, the returned type is set to Oservable.
Guide Package:
‘io.reactivex:rxjava:1.1.3‘ ‘io.reactivex:rxandroid:1.1.0‘ ‘com.squareup.retrofit2:retrofit:2.0.2‘ ‘com.squareup.retrofit2:converter-gson:2.0.2‘ ‘com.squareup.retrofit2:converter-scalars:2.0.2‘ ‘com.squareup.retrofit2:adapter-rxjava:2.0.2‘ ‘com.jakewharton:butterknife:7.0.1‘ ‘com.squareup.okhttp3:okhttp:3.2.0‘ ‘com.squareup.okio:okio:1.8.0‘
Encounter some pits here, if the following three less one, return to his unsupported results, will crash, which is why the above is the reason why so many packets.
privatestaticgetRetrofit(String url) { returnnew Retrofit.Builder().baseUrl(url) //增加返回值为String的支持 .addConverterFactory(ScalarsConverterFactory.create()) //增加返回值为Gson的支持(以实体类返回) .addConverterFactory(GsonConverterFactory.create()) //增加返回值为Oservable<T>的支持 .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); }
GET Request:
http://wthrcdn.etouch.cn/weather_mini?city= Shenzhen
publicinterface IWeather { @GET("/weather_mini") Observable<Weather> getWeather(@Query("city") String city);}
publicstaticfinal"http://wthrcdn.etouch.cn"publicstaticgetIWeather() { return getRetrofit(url_weather).create(IWeather.class); }
Httputil. Getiweather(). GetWeather("Shenzhen"). Subscribeon(schedulers. IO()). Observeon(androidschedulers. Mainthread()). Subscribe(New action1<weather> () {@Override public voidPager(Weather Weather) {TV. SetText(Weather. GetData(). Getganmao());} });
POST request:
According to the background, multipart or formurlencoded, if you do not know the best two to try, I also met the big hole here, if the way is wrong, the post does not go up.
Multipart (This is the use of their own server, the latter people see this blog may not use this API)
http://122.114.38.95:8857
parameter is action, if Action=banner can return correct result otherwise error result
@Multipart @POST("/") Observable<String> getBanner(@Part("action") String action);
publicstaticfinal"http://122.114.38.95:8857";publicstaticgetBanner() { return getRetrofit(url_bannertest).create(IBannerTest.class); }
httputil.getBanner ( ) .getbanner ( "banner" ) .subscribeon (Schedulers.io ()) .observeon (Androidschedulers.mainthread ()) .subscribe (New action1<string> () {@Override publi c void call (String s) {tv.settext (s) ; }})
formurlencoded: (URL in the tutorial)
Http://www.w3school.com.cn/ajax/demo_post2.asp
Parameter Fname,lname
@FormUrlEncoded @POST("/ajax/demo_post2.asp") Observable<String> postW3c(@Field("fname") String fname, @Field("lname") String lname);
public Static final String w3c_url = "HTTP +/ Www.w3school.com.cn "; public static IW3C getiw3c () {return getretrofit (w3c_url). CRE Ate (Iw3c.class); }
Httputil.getIW 3C () Span class= "Hljs-preprocessor" >.POSTW 3c ( "Long" , "Hoyn" ) .subscribeon (Schedulers.io ()) .observeon (Androidschedulers.mainthread ()) .subscribe (New action1<string> () {@Override publi c void call (String s) {tv.settext (s) ; }})
Post Upload Image:
Here is the interface with the image++.
Http://apicn.imageplusplus.com/analyze?
Parameters: Api_key,api_secret, img
@Multipart @POST("/analyze") Observable<String> upLoadImage( @Part("api_key"String api_key, @Part ("api_secret"String api_secret,@Part MultipartBody.Part file );
publicstaticfinal"http://apicn.imageplusplus.com"publicstaticgetIImagePP() { return getRetrofit(imagepp_url).create(IImagePP.class); publicstaticpostFileParams(String key, File file) { RequestBody fileBody = RequestBody.create(MediaType.parse("image/*"), file); return MultipartBody.Part.createFormData(key, file.getName(), fileBody); }
File File = new file (environment. getExternalStorageDirectory()+"/123.png");Httputil. Getiimagepp(). Uploadimage("C1a2b3ab56a2f218aed9b2ab3c16ce88","be8318b73cef1c2bcafb6c8a77922436", Httputil. Postfileparams("img", file)). Subscribeon(schedulers. IO()). Observeon(androidschedulers. Mainthread()). Subscribe(New action1<string> () {@Override public voidPager(String s) {TV. SetText(s);} });
The Okhttp feature is used here, which is why you should import okhttp.
private static Retrofit getRetrofit(String url) { return new Retrofit.Builder().baseUrl(url) .addConverterFactory(ScalarsConverterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); }
It says retrofit added 3 sentences.
Scalarsconverterfactory is a supported return string type
Gsonconverterfactory is support for returning entity classes.
Rxjavacalladapterfactory is a observable that supports returning Rxjava.
The above example GET request used Gsonconverterfactory and rxjavacalladapterfactory.
Post used scalarsconverterfactory and rxjavacalladapterfactory.
Less one will jump, so everyone use retrofit need to pay attention to this point.
It's time to get to know a wave of Retrofit2.