Android使用Retrofit2.0和RxJava2.0处理网络请求
生活随笔
收集整理的這篇文章主要介紹了
Android使用Retrofit2.0和RxJava2.0处理网络请求
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
首先使用SpringBoot創建一個簡單的SpringMVC工程。
@RestController public class RetrofitController {@RequestMapping("/users/{user}")public User getUser(@PathVariable("user") String u){System.out.println("user = " + u);User user = new User();user.setUsername("test");user.setEmail(("test@qq.com"));return user;} }public class User {private String username;private String email;public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;} }
服務端運行在8000端口。
通過Android Studio創建一個Android工程。
在AndroidManifest.xml添加
<uses-permission android:name="android.permission.INTERNET"/>在build.gradle添加發下代碼,使用Retrofit2.2.0, RxJava2.0.7, RxAndroid2.0, 1, gson 2.8.0
compile 'com.squareup.retrofit2:retrofit:2.2.0' compile 'com.squareup.retrofit2:adapter-rxjava2:2.2.0' //compile 'com.squareup.retrofit2:converter-jackson:2.2.0' compile 'com.squareup.retrofit2:converter-gson:2.2.0' compile 'com.google.code.gson:gson:2.8.0' compile 'io.reactivex.rxjava2:rxandroid:2.0.1' compile 'io.reactivex.rxjava2:rxjava:2.0.7'定義UserService
public interface UserService {@GET("/users/{user}")Flowable<User> getUser(@Path("user") String user); }測試代碼 protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);// 只是例子,沒有采用注解方案//后續可以添加token處理, cache處理, 請求攔截等功能tvResponse = (TextView) findViewById(R.id.tvResponse);btnRequest = (Button) findViewById(R.id.btnTest);btnRequest.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {Log.d(TAG, "test");Retrofit retrofit = new Retrofit.Builder().baseUrl("http://10.0.0.16:8000/").addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJava2CallAdapterFactory.create()).build();UserService userService = retrofit.create(UserService.class);userService.getUser("chenhaifeng2016").subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<User>() {@Overridepublic void onSubscribe(Subscription s) {s.request(Long.MAX_VALUE);}@Overridepublic void onNext(User user) {Log.d(TAG, "成功");Log.d(TAG, "response=" + user.getUsername());}@Overridepublic void onError(Throwable t) {Log.d(TAG, "出錯");}@Overridepublic void onComplete() {Log.d(TAG, "完成");}});}});
運行效果
03-16 21:14:15.283 312-312/cssweb.com.retrofit2demo D/MainActivity: test
03-16 21:14:15.313 312-312/cssweb.com.retrofit2demo D/MainActivity: 成功
03-16 21:14:15.313 312-312/cssweb.com.retrofit2demo D/MainActivity: response=test
03-16 21:14:15.313 312-312/cssweb.com.retrofit2demo D/MainActivity: 完成
完整工程源代碼
https://github.com/chenhaifeng2016/Retrofit2Demo
總結
以上是生活随笔為你收集整理的Android使用Retrofit2.0和RxJava2.0处理网络请求的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ubuntu 16.04 安装Tenso
- 下一篇: 推荐ReactNative脚手架工具