我将使用rxJava和改造发送获取请求。我这样做的方式是我创建了POST
模型和一个名为ApiCall
的接口,我还在gradle中添加了以下依赖项:
compile 'com.squareup.retrofit2:retrofit:2.2.0'
compile 'com.android.support:recyclerview-v7:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'io.reactivex.rxjava2:rxjava:2.0.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.0'
compile 'com.google.code.gson:gson:2.4'
在ApiCall
界面中,我这样做:
public interface ApiCall {
String SERVICE_ENDPOINT = "https://myserverIp";
@GET("/api/post")
io.reactivex.Observable<Post> getPost();
}
在我的活动的onResume()
中,我是这样的:
@Override
protected void onResume() {
super.onResume();
Retrofit retrofit=new Retrofit.Builder()
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://198.50.214.15/")
.build();
ApiCall apiService=retrofit.create(ApiCall.class);
Observable<Post> observable=apiService.getPost();
observable.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(responseData -> {
messageList.add(responseData.getTitle());
postAdapter.notifyDataSetChanged();
});
}
最后我得到这个错误:
Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'.
> com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK META-INF/rxjava.properties
File1: /home/hussein/.gradle/caches/modules-2/files-2.1/io.reactivex.rxjava2/rxjava/2.0.1/57f850a6b317e5582f1dbaff10a9e7d7e1fcdcfb/rxjava-2.0.1.jar
File2: /home/hussein/.gradle/caches/modules-2/files-2.1/io.reactivex/rxjava/1.1.1/b494968f6050d494de55dc3ce005e59c7eb40012/rxjava-1.1.1.jar
您必须从packagingOptions
中排除该文件:
android {
...
packagingOptions {
exclude 'META-INF/rxjava.properties'
}
}